<?php
/**
 * 点大商城（www.diandashop.com） - 微信公众号小程序商城系统!
 * Copyright © 2020 山东点大网络科技有限公司 保留所有权利
 * =========================================================
 * 版本：V2
 * 授权主体：shop.guanjunbang.cn
 * 授权域名：shop.guanjunbang.cn
 * 授权码：vdcajlVLIVAgVdkfJvgY
 * ----------------------------------------------
 * 您只能在商业授权范围内使用，不可二次转售、分发、分享、传播
 * 任何企业和个人不得对代码以任何目的任何形式的再发布
 * =========================================================
 */

namespace app\controller;
use think\facade\Db;
class ApiMy extends ApiCommon
{
	public function initialize(){
		parent::initialize();
		$this->checklogin();
	}
	public function getWebinfo()
	{
		$rs = Db::name('admin_set')->where('aid',aid)->find();
		if($rs){
			return $this->json($rs);
		}else{
			return $this->json(['status'=>0,'msg'=>'页面不存在']);
		}
	}
	public function usercenter(){

        \app\custom\HuiDong::syncMemberSingle(aid,mid);

		if(getcustom('plug_tengrui')){
			//全部同步认证
			$tengrui = new \app\custom\TengRui(aid,mid);
			$tengrui->tb_dan_member($this->member['mpopenid']);
		}
		$pagedata = Db::name('designerpage')->where('aid',aid)->where('ishome',2)->find();
		if($pagedata){
			$pageinfo = json_decode($pagedata['pageinfo'],true);
			$pagecontent = json_decode(\app\common\System::initpagecontent($pagedata['content'],aid,mid,platform),true);

			$rdata = [];
			$rdata['status'] = 1;
			$rdata['msg'] = '查询成功';
			$rdata['pageinfo'] = $pageinfo[0]['params'];
			$rdata['pagecontent'] = $pagecontent;
			$rdata['copyright'] = Db::name('admin')->where('id',aid)->value('copyright');
			if(getcustom('xixie')){
				$rdata['xixie'] = false;
				if($this->member && $this->member['mdid']>0){
					//查询洗鞋插件是否开启
					$xixie_sysset = Db::name('xixie_sysset')->where('aid',aid)->find();
		            if($xixie_sysset && $xixie_sysset['all_close'] == 0){
		            	$count_mendian = Db::name('mendian')->where('id',$this->member['mdid'])->where('aid',aid)->count();
						if($count_mendian){
							$rdata['xixie'] = true;
						}
		            }
				}
			}
			return $this->json($rdata);
		}else{
			return $this->json(['status'=>0,'msg'=>'页面不存在']);
		}
	}
	public function set(){
		$smsset = Db::name('admin_set_sms')->where('aid',aid)->find();
		if($smsset && $smsset['status'] == 1 && $smsset['tmpl_smscode'] && $smsset['tmpl_smscode_st']==1){
			$needsms = 1;
		}else{
			$needsms = 0;
		}
		if(request()->isPost()){
			$formdata = input('post.info/a');
			if($needsms==1){
				if(md5($formdata['tel'].'-'.$formdata['code']) != cache(input('param.session_id').'_smscode') || cache(input('param.session_id').'_smscodetimes') > 5){
					return $this->json(['status'=>0,'msg'=>'短信验证码错误']);
				}
			}
			cache(input('param.session_id').'_smscode',null);
			cache(input('param.session_id').'_smscodetimes',null);
			$province_city = explode(' ',$formdata['province_city']);
			$info = [];
			$info['realname'] = $formdata['realname'];
			$info['tel'] = $formdata['tel'];
			$info['usercard'] = $formdata['usercard'];
			$info['weixin'] = $formdata['weixin'];
			$info['aliaccount'] = $formdata['aliaccount'];
			$info['bankname'] = $formdata['bankname'];
			$info['bankcarduser'] = $formdata['bankcarduser'];
			$info['bankcardnum'] = $formdata['bankcardnum'];
			$info['sex'] = $formdata['sex'];
			$info['province'] = $province_city[0];
			$info['city'] = $province_city[1];
			$info['birthday'] = $formdata['birthday'];
			Db::name('member')->where('id',mid)->update($info);
			return $this->json(['status'=>1,'msg'=>'修改成功']);
		}
		$userinfo = Db::name('member')->where('id',mid)->field('id,headimg,nickname,realname,tel,usercard,weixin,aliaccount,aliaccountname,bankname,bankaddress,bankcarduser,bankcardnum,sex,province,city,birthday')->find();
		if($userinfo['realname'] == null) $userinfo['realname'] = '';
		if($userinfo['tel'] == null) $userinfo['tel'] = '';
		if($userinfo['usercard'] == null) $userinfo['usercard'] = '';
		if($userinfo['weixin'] == null) $userinfo['weixin'] = '';
		if($userinfo['aliaccount'] == null) $userinfo['aliaccount'] = '';
		if($userinfo['aliaccountname'] == null) $userinfo['aliaccountname'] = '';
		if($userinfo['bankname'] == null) $userinfo['bankname'] = '';
		if($userinfo['bankcarduser'] == null) $userinfo['bankcarduser'] = '';
		if($userinfo['bankcardnum'] == null) $userinfo['bankcardnum'] = '';
		if($userinfo['bankaddress'] == null) $userinfo['bankaddress'] = '';
		if($userinfo['sex'] == null) $userinfo['sex'] = '';
		if($userinfo['province'] == null) $userinfo['province'] = '';
		if($userinfo['city'] == null) $userinfo['city'] = '';
		if($userinfo['birthday'] == null) $userinfo['birthday'] = '';
		if($this->member['pwd']==''){
			$userinfo['haspwd'] = 0;
		}else{
			$userinfo['haspwd'] = 1;
		}

		$rdata = [];
		$rdata['needsms'] = $needsms;
		$rdata['userinfo'] = $userinfo;
		return $this->json($rdata);
	}
	public function setfield(){
		$headimg = input('post.headimg');
		$nickname = input('post.nickname');
		$realname = input('post.realname');
		$sex = input('post.sex');
		$birthday = input('post.birthday');
		$weixin = input('post.weixin');
		$aliaccount = input('post.aliaccount');
		$aliaccountname = input('post.aliaccountname');
		$bankname = input('post.bankname');
		$bankcarduser = input('post.bankcarduser');
		$bankcardnum = input('post.bankcardnum');
		$bankaddress = input('post.bankaddress');
		$data = [];
		if($headimg) $data['headimg'] = $headimg;
		if($nickname) $data['nickname'] = $nickname;
		if($realname) $data['realname'] = $realname;
		if($sex) $data['sex'] = $sex;
		if($birthday) $data['birthday'] = $birthday;
		if($weixin) $data['weixin'] = $weixin;
		if($aliaccount) $data['aliaccount'] = $aliaccount;
		if($aliaccountname) $data['aliaccountname'] = $aliaccountname;
		if($bankname) $data['bankname'] = $bankname;
		if($bankcarduser) $data['bankcarduser'] = $bankcarduser;
		if($bankcardnum) $data['bankcardnum'] = $bankcardnum;
		if($bankaddress) $data['bankaddress'] = $bankaddress;
		Db::name('member')->where('id',mid)->update($data);
		if($headimg || $nickname) {
		    //删除海报
            Db::name('member_poster')->where('aid',aid)->where(['mid'=>mid])->delete();
        }
		$member = Db::name('member')->where('id',mid)->find();
		if($member['is_wanshan_score'] == 0 && $member['realname'] && $member['tel'] && $member['sex'] && $member['birthday']){
			Db::name('member')->where('id',mid)->update(['is_wanshan_score'=>1]);
			$set = Db::name('register_giveset')->where('aid',aid)->find();
			if($set['status']==1 && $set['wanshan_score']>0){
				$date = date('Y-m-d H:i:s');
				if($date >= $set['starttime'] && $date < $set['endtime']){
					\app\common\Member::addscore(aid,mid,$set['wanshan_score'],'完善资料赠送');
				}
			}
		}
		return $this->json(['status'=>1,'msg'=>'修改成功']);
	}
	//编辑手机号
	public function settel(){
		$smsset = Db::name('admin_set_sms')->where('aid',aid)->find();
		if($smsset && $smsset['status'] == 1 && $smsset['tmpl_smscode'] && $smsset['tmpl_smscode_st']==1){
			$needsms = true;
		}else{
			$needsms = false;
		}
		$rdata = [];
		$rdata['status'] = 1;
		$rdata['needsms'] = $needsms;
		return $this->json($rdata);
	}
	public function settelsub(){
		$tel = input('param.tel');
		$smscode = input('param.smscode');
		$smsset = Db::name('admin_set_sms')->where('aid',aid)->find();
		if($smsset && $smsset['status'] == 1 && $smsset['tmpl_smscode'] && $smsset['tmpl_smscode_st']==1){
			$needsms = true;
		}else{
			$needsms = false;
		}
		if($needsms && md5($tel.'-'.$smscode) != cache($this->sessionid.'_smscode') || cache($this->sessionid.'_smscodetimes')>5){
			cache($this->sessionid.'_smscodetimes',cache($this->sessionid.'_smscodetimes')+1);
			return $this->json(['status'=>0,'msg'=>'短信验证码错误']);
		}
		$member = Db::name('member')->where('aid',aid)->where('id','<>',mid)->where('tel',$tel)->find();
		if($member){
			return $this->json(['status'=>0,'msg'=>'该手机号已绑定其他账号']);
		}

		cache($this->sessionid.'_smscode',null);
		cache($this->sessionid.'_smscodetimes',null);
		Db::name('member')->where('id',mid)->update(['tel'=>$tel]);
		return $this->json(['status'=>1,'msg'=>'修改成功']);

	}
	//修改密码
	public function setpwd(){
		if($this->member['pwd']==''){
			$haspwd = 0;
		}else{
			$haspwd = 1;
		}
		if(request()->isPost()){
			$pwd = input('post.pwd');
			$oldpwd = input('post.oldpwd');
			if($this->member['pwd'] && $this->member['pwd'] != md5($oldpwd)){
				return $this->json(['status'=>0,'msg'=>'原密码输入错误']);
			}
			Db::name('member')->where('aid',aid)->where('id',mid)->update(['pwd'=>md5($pwd)]);
			return $this->json(['status'=>1,'msg'=>'修改成功']);
		}
		$rdata = [];
		$rdata['haspwd'] = $haspwd;
		return $this->json($rdata);
	}
	//支付密码设置
	public function paypwd(){
		if($this->member['paypwd']==''){
			$haspwd = 0;
		}else{
			$haspwd = 1;
		}
		if(request()->isPost()){
			$paypwd = input('post.paypwd');
			$oldpaypwd = input('post.oldpaypwd');
			if($this->member['paypwd'] && $this->member['paypwd'] != $oldpaypwd){
				return $this->json(['status'=>0,'msg'=>'原密码输入错误']);
			}
			Db::name('member')->where('aid',aid)->where('id',mid)->update(['paypwd'=>$paypwd]);
			return $this->json(['status'=>1,'msg'=>'修改成功']);
		}
		$rdata = [];
		$rdata['haspwd'] = $haspwd;
		return $this->json($rdata);
	}
	public function withdraw(){
		$set = Db::name('admin_set')->where('aid',aid)->field('withdraw_autotransfer,withdraw,withdrawmin,withdrawfee,withdraw_weixin,withdraw_aliaccount,withdraw_bankcard')->find();
		if(request()->isPost()){
			$post = input('post.');
			if($set['withdraw'] == 0){
				return $this->json(['status'=>0,'msg'=>t('余额').'提现功能未开启']);
			}
			if($post['paytype']=='支付宝' && $this->member['aliaccount']==''){
                if($set['withdraw_aliaccount'] == 0)
                    return $this->json(['status'=>0,'msg'=>'支付宝提现功能未开启']);
				return $this->json(['status'=>0,'msg'=>'请先设置支付宝账号']);
			}
			if($post['paytype']=='银行卡' && ($this->member['bankname']==''||$this->member['bankcarduser']==''||$this->member['bankcardnum']=='')){
                if($set['withdraw_bankcard'] == 0)
                    return $this->json(['status'=>0,'msg'=>'银行卡提现功能未开启']);
                return $this->json(['status'=>0,'msg'=>'请先设置完整银行卡信息']);
			}
            if($post['paytype'] == '微信钱包' && $set['withdraw_weixin'] == 0){
                return $this->json(['status'=>0,'msg'=>'微信钱包提现功能未开启']);
            }

			$money = $post['money'];
			if($money<=0 || $money < $set['withdrawmin']){
				return $this->json(['status'=>0,'msg'=>'提现金额必须大于'.($set['withdrawmin']?$set['withdrawmin']:0)]);
			}
			if($money > $this->member['money']){
				return $this->json(['status'=>0,'msg'=>'可提现'.t('余额').'不足']);
			}

			$ordernum = date('ymdHis').aid.rand(1000,9999);
			$record['aid'] = aid;
			$record['mid'] = mid;
			$record['createtime']= time();
			$record['money'] = $money*(1-$set['withdrawfee']*0.01);
			if($record['money'] <= 0) {
                return $this->json(['status'=>0,'msg'=>'提现金额有误']);
            }
            $record['money'] = round($record['money'],2);
			$record['txmoney'] = $money;
			if($post['paytype']=='支付宝'){
				$record['aliaccountname'] = $this->member['aliaccountname'];
				$record['aliaccount'] = $this->member['aliaccount'];
			}
			if($post['paytype']=='银行卡'){
				$record['bankname'] = $this->member['bankname'] . ($this->member['bankaddress'] ? ' '.$this->member['bankaddress'] : '');
				$record['bankcarduser'] = $this->member['bankcarduser'];
				$record['bankcardnum'] = $this->member['bankcardnum'];
			}
			$record['ordernum'] = $ordernum;
			$record['paytype'] = $post['paytype'];
			$record['platform'] = platform;
			$recordid = Db::name('member_withdrawlog')->insertGetId($record);

			\app\common\Member::addmoney(aid,mid,-$money,t('余额').'提现');

			$tmplcontent = array();
			$tmplcontent['first'] = '有客户申请'.t('余额').'提现';
			$tmplcontent['remark'] = '点击进入查看~';
			$tmplcontent['keyword1'] = $this->member['nickname'];
			$tmplcontent['keyword2'] = date('Y-m-d H:i');
			$tmplcontent['keyword3'] = $money.'元';
			$tmplcontent['keyword4'] = $post['paytype'];
			\app\common\Wechat::sendhttmpl(aid,0,'tmpl_withdraw',$tmplcontent,m_url('admin/finance/withdrawlog'));
			
			$tmplcontent = [];
			$tmplcontent['name3'] = $this->member['nickname'];
			$tmplcontent['amount1'] = $money.'元';
			$tmplcontent['date2'] = date('Y-m-d H:i');
			$tmplcontent['thing4'] = '提现到'.$post['paytype'];
			\app\common\Wechat::sendhtwxtmpl(aid,0,'tmpl_withdraw',$tmplcontent,'admin/finance/withdrawlog');


			if($set['withdraw_autotransfer'] && ($post['paytype'] = '微信钱包' || $post['paytype'] = '银行卡')){
                Db::name('member_withdrawlog')->where('id',$recordid)->update(['status' => 1]);
				$rs = \app\common\Wxpay::transfers(aid,mid,$record['money'],$record['ordernum'],platform,t('余额').'提现');
				if($rs['status']==0){
					return json(['status'=>1,'msg'=>'提交成功,请等待打款']);
				}else{
                    Db::name('member_withdrawlog')->where('id',$recordid)->update(['status' => 3]);
					Db::name('member_withdrawlog')->where('aid',aid)->where('id',$recordid)->update(['status'=>3,'paytime'=>time(),'paynum'=>$rs['resp']['payment_no']]);
					//提现成功通知
					$tmplcontent = [];
					$tmplcontent['first'] = '您的提现申请已打款，请留意查收';
					$tmplcontent['remark'] = '请点击查看详情~';
					$tmplcontent['money'] = (string) round($record['money'],2);
					$tmplcontent['timet'] = date('Y-m-d H:i',$record['createtime']);
					\app\common\Wechat::sendtmpl(aid,$record['mid'],'tmpl_tixiansuccess',$tmplcontent,m_url('pages/my/usercenter'));
					//订阅消息
					$tmplcontent = [];
					$tmplcontent['amount1'] = $record['money'];
					$tmplcontent['thing3'] = '微信打款';
					$tmplcontent['time5'] = date('Y-m-d H:i');
					
					$tmplcontentnew = [];
					$tmplcontentnew['amount3'] = $record['money'];
					$tmplcontentnew['phrase9'] = '微信打款';
					$tmplcontentnew['date8'] = date('Y-m-d H:i');
					\app\common\Wechat::sendwxtmpl(aid,$record['mid'],'tmpl_tixiansuccess',$tmplcontentnew,'pages/my/usercenter',$tmplcontent);
					//短信通知
					if($this->member['tel']){
						\app\common\Sms::send(aid,$this->member['tel'],'tmpl_tixiansuccess',['money'=>$record['money']]);
					}
					return json(['status'=>1,'msg'=>$rs['msg']]);
				}
			}

			return $this->json(['status'=>1,'msg'=>'提交成功,请等待打款']);
		}
		$userinfo = Db::name('member')->where('id',mid)->field('id,money,aliaccount,bankname,bankcarduser,bankcardnum')->find();
		//订阅消息
		$wx_tmplset = Db::name('wx_tmplset')->where('aid',aid)->find();
		$tmplids = [];
		if($wx_tmplset['tmpl_tixiansuccess_new']){
			$tmplids[] = $wx_tmplset['tmpl_tixiansuccess_new'];
		}elseif($wx_tmplset['tmpl_tixiansuccess']){
			$tmplids[] = $wx_tmplset['tmpl_tixiansuccess'];
		}
		if($wx_tmplset['tmpl_tixianerror_new']){
			$tmplids[] = $wx_tmplset['tmpl_tixianerror_new'];
		}elseif($wx_tmplset['tmpl_tixianerror']){
			$tmplids[] = $wx_tmplset['tmpl_tixianerror'];
		}
		$rdata = [];
		$rdata['userinfo'] = $userinfo;
		$rdata['sysset'] = $set;
		$rdata['tmplids'] = $tmplids;
		return $this->json($rdata);
	}
	public function moneylog(){
		$st = input('param.st');
		$pagenum = input('post.pagenum');
		if(!$pagenum) $pagenum = 1;
		$pernum = 20;
		$where = [];
		$where[] = ['aid','=',aid];
		$where[] = ['mid','=',mid];
		if($st == 1){//充值记录
			$datalist = Db::name('recharge_order')->field("id,money,`status`,from_unixtime(createtime) createtime")->where($where)->where('status=1')->page($pagenum,$pernum)->order('id desc')->select()->toArray();
			if(!$datalist) $datalist = [];
		}elseif($st ==2){//提现记录
			$datalist = Db::name('member_withdrawlog')->field("id,money,txmoney,`status`,from_unixtime(createtime) createtime")->where($where)->page($pagenum,$pernum)->order('id desc')->select()->toArray();
			if(!$datalist) $datalist = [];
		}else{ //余额明细
			$datalist = Db::name('member_moneylog')->field("id,money,`after`,from_unixtime(createtime) createtime,remark")->where($where)->page($pagenum,$pernum)->order('id desc')->select()->toArray();
			if(!$datalist) $datalist = [];
			foreach($datalist as $k=>$v){
				if(strpos($v['remark'],'商家充值，') === 0){
					$datalist[$k]['remark'] = '商家充值';
				}
			}
		}
		if($pagenum == 1){
			$canwithdraw = Db::name('admin_set')->where('aid',aid)->value('withdraw');
		}
		return $this->json(['status'=>1,'data'=>$datalist,'canwithdraw'=>$canwithdraw]);
	}
	public function scorelog(){
		$pagenum = input('post.pagenum');
        $st = input('post.st');
		if(!$pagenum) $pagenum = 1;
		$pernum = 20;
		$where = [];
		$where[] = ['aid','=',aid];
		$where[] = ['mid','=',mid];
		$datalist = Db::name('member_scorelog')->field('id,score,after,remark,from_unixtime(createtime)createtime')->where($where)->page($pagenum,$pernum)->order('id desc')->select()->toArray();
		if(!$datalist) $datalist = [];
		if(request()->isPost()){
		    if($pagenum == 1) {
                $set = Db::name('admin_set')->where('aid', aid)->find();
                $scoreTransfer = $set['score_transfer'] ? true : false;
                $scoreWithdraw = $set['score_withdraw'] ? true : false;
            }

            return $this->json(['status'=>1,'data'=>$datalist,'myscore'=>$this->member['score'],'score_withdraw'=>$this->member['score_withdraw'], 'scoreTransfer' => $scoreTransfer, 'scoreWithdraw' => $scoreWithdraw] );
		}

		$count = Db::name('member_scorelog')->where($where)->count();

		$rdata = [];
		$rdata['count'] = $count;
		$rdata['datalist'] = $datalist;
		$rdata['pernum'] = $pernum;
		$rdata['st'] = $st;
		$rdata['myscore'] = $this->member['score'];
        return $this->json($rdata);
	}

    public function scoreTransfer()
    {
        if(getcustom('score_transfer')){
            //积分转送
            $set = Db::name('admin_set')->where('aid', aid)->find();
            if ($set['score_transfer'] != 1) {
                return $this->json(['status'=>0,'msg'=>t('积分').'转赠未开启']);
            }
            if(request()->isPost()){
                $mobile = input('post.mobile');
                $mid = input('post.mid/d');
                $integral = input('post.integral/d');
                if ($integral <= 0){
                    return $this->json(['status'=>0,'msg'=>'请输入正确的'.t('积分').'数量']);
                }
                if (input('?post.mobile')) {
                    $info = Db::name('member')->where('aid', aid)->where('tel', $mobile)->find();
                }
                if (input('?post.mid')) {
                    $info = Db::name('member')->where('aid', aid)->where('id', $mid)->find();
                }

                if(!$info) return $this->json(['status'=>0,'msg'=>'未找到该'.t('会员')]);
                $user_id = $info['id'];

                if ($info['id'] == mid) {
                    return $this->json(['status'=>0,'msg'=>'不能转赠给自己']);
                }
                if ($integral > $this->member['score']){
                    return $this->json(['status'=>0,'msg'=>'您的'.t('积分').'数量不足']);
                }
                $where = [];
                $where['aid'] = aid;
                $where['id'] = $user_id;
                $rs = \app\common\Member::addscore(aid,mid,$integral * -1, sprintf(t('积分')."转赠给：%s",$info['nickname']));
                if ($rs['status'] == 1) {
                    \app\common\Member::addscore(aid,$user_id,$integral,sprintf("来自%s的".t('积分')."转赠", $this->member["nickname"]));
                }else{
                    return $this->json(['status'=>0, 'msg' => '转赠失败']);
                }
                return $this->json(['status'=>1, 'msg' => '转赠成功', 'url'=>m_url('my/usercenter').'/aid/'.aid]);
            }

            $rdata['status'] = 1;
            $rdata['myscore'] = $this->member['score'];
            return $this->json($rdata);
        }
    }

    public function scoreWithdraw()
    {
        if(getcustom('score_withdraw')){
            //积分转到余额
            $set = Db::name('admin_set')->where('aid', aid)->find();
            if ($set['score_withdraw'] != 1) {
                return $this->json(['status'=>0,'msg'=>t('积分').'提现未开启']);
            }
            if(request()->isPost()){
                $integral = input('post.integral/d');
                if ($integral <= 0){
                    return $this->json(['status'=>0,'msg'=>'请输入正确的'.t('积分').'数量']);
                }
                if ($integral > $this->member['score_withdraw']){
                    return $this->json(['status'=>0,'msg'=>'您的'.t('积分').'数量不足']);
                }
                $where = [];
                $where['aid'] = aid;
                $where['id'] = mid;
                $money = round($integral * $set['score_to_money_percent'],2);
                if($money < 0.01) {
                    return $this->json(['status'=>0,'msg'=>'提现金额不足0.01']);
                }
                $rs = \app\common\Member::addmoney(aid,mid,$money,'允提'.t('积分').'提现');
                if ($rs['status'] == 1) {
                    \app\common\Member::addscore_withdraw(aid,mid,$integral * -1, '允提'.t('积分').'提现');
                }
                return $this->json(['status'=>1, 'msg' => '操作成功', 'url'=>m_url('my/usercenter').'/aid/'.aid]);
            }

            $rdata['status'] = 1;
            $rdata['myscore'] = $this->member['score_withdraw'];
            $rdata['score_to_money_percent'] = $set['score_to_money_percent']+0;
            return $this->json($rdata);
        }
    }

	public function formlog(){
		$pagenum = input('post.pagenum');
        $st = input('post.st');
		if(!$pagenum) $pagenum = 1;
		$pernum = 20;
		$where = [];
		$where[] = ['aid','=',aid];
		$where[] = ['mid','=',mid];
		$where[] = ['isudel','=',0];
		
		if(input('post.keyword')){
			$where[] = ['title|form0|form1|form2|form3|form4|form5|form6|form7|form8|form9|form10','like','%'.input('param.keyword').'%'];
		}

		if(!input('?param.st') || $st === ''){
			$st = 'all';
		}
		if($st == 'all'){

		}elseif($st == '0'){
			$where[] = ['status','=',0];
			$where[] = Db::raw('payorderid is null or paystatus=1');
		}elseif($st == '1'){
			$where[] = ['status','=',1];
		}elseif($st == '2'){
			$where[] = ['status','=',2];
		}elseif($st == '10'){
			$where[] = ['status','=',0];
			$where[] = ['paystatus','=',0];
			$where[] = ['payorderid','<>',''];
		}

		//$where['status'] = 1;
		$datalist = Db::name('form_order')->field('*,from_unixtime(createtime)createtime,from_unixtime(paytime)paytime')->where($where)->page($pagenum,$pernum)->order('id desc')->select()->toArray();
		if(!$datalist) $datalist = [];
		if(request()->isPost()){
			return $this->json(['status'=>1,'data'=>$datalist]);
		}
		$count = Db::name('form_order')->where($where)->count();
		$rdata = [];
		$rdata['count'] = $count;
		$rdata['datalist'] = $datalist;
		$rdata['pernum'] = $pernum;
		$rdata['st'] = $st;
		return $this->json($rdata);
	}
    public function formlog2(){
	    if(!getcustom('form_log_plug')){
	        return false;
        }
        $pagenum = input('post.pagenum');
        $st = input('post.st');
        $id = input('post.id');
        if(!$pagenum) $pagenum = 1;
        $pernum = 20;
        $where = [];
        $where[] = ['aid','=',aid];
        $where[] = ['isudel','=',0];
        $where[] = ['formid','=',$id];

		if(input('post.keyword')){
			$where[] = ['title|form0|form1|form2|form3|form4|form5|form6|form7|form8|form9|form10','like','%'.input('param.keyword').'%'];
		}

        if(!input('?param.st') || $st === ''){
            $st = 'all';
        }
        if($st == 'all'){

        }elseif($st == '0'){
            $where[] = ['status','=',0];
            $where[] = Db::raw('payorderid is null or paystatus=1');
        }elseif($st == '1'){
            $where[] = ['status','=',1];
        }elseif($st == '2'){
            $where[] = ['status','=',2];
        }elseif($st == '10'){
            $where[] = ['status','=',0];
            $where[] = ['paystatus','=',0];
            $where[] = ['payorderid','<>',''];
        }

        //$where['status'] = 1;
        $datalist = Db::name('form_order')->field('*,from_unixtime(createtime)createtime,from_unixtime(paytime)paytime')->where($where)->page($pagenum,$pernum)->order('id desc')->select()->toArray();
        if(!$datalist) $datalist = [];
        else {
            foreach ($datalist as $k => $item) {
            	//处理前四条提交类型
            	$datalist[$k]['form0_key'] = '';
            	$datalist[$k]['form1_key'] = '';
            	$datalist[$k]['form2_key'] = '';
            	$datalist[$k]['form3_key'] = '';

            	$datalist[$k]['form0_val'] = '';
            	$datalist[$k]['form1_val'] = '';
            	$datalist[$k]['form2_val'] = '';
            	$datalist[$k]['form3_val'] = '';
            	$datalist[$k]['member'] = '';
            	if($item['mid']){
            		 $datalist[$k]['member'] = \db('member')->where('aid',aid)->where('id',$item['mid'])->field('nickname,realname')->find();
            		 $datalist[$k]['member']['nickname'] = $datalist[$k]['member']['nickname'] && !is_null($datalist[$k]['member']['nickname'])?$datalist[$k]['member']['nickname']:'';
            		 $datalist[$k]['member']['realname'] = $datalist[$k]['member']['realname'] && !is_null($datalist[$k]['member']['realname'])?$datalist[$k]['member']['realname']:'';
            	}
                $form = Db::name('form')->where('aid',aid)->where('id',$item['formid'])->find();
				$formcontent = json_decode($form['content'],true);
				if($formcontent){
					if($formcontent[0]){
						$datalist[$k]['form0_key'] = $formcontent[0]['key'];
						$datalist[$k]['form0_val'] = $formcontent[0]['val1'];
					}
					if($formcontent[1]){
						$datalist[$k]['form1_key'] = $formcontent[1]['key'];
						$datalist[$k]['form1_val'] = $formcontent[1]['val1'];
					}
					if($formcontent[2]){
						$datalist[$k]['form2_key'] = $formcontent[2]['key'];
						$datalist[$k]['form2_val'] = $formcontent[2]['val1'];
					}
					if($formcontent[3]){
						$datalist[$k]['form3_key'] = $formcontent[3]['key'];
						$datalist[$k]['form3_val'] = $formcontent[3]['val1'];
					}
				}
            }
        }
        if(request()->isPost()){
            return $this->json(['status'=>1,'data'=>$datalist]);
        }
        $count = Db::name('form_order')->where($where)->count();
        $rdata = [];
        $rdata['count'] = $count;
        $rdata['datalist'] = $datalist;
        $rdata['pernum'] = $pernum;
        $rdata['st'] = $st;
        return $this->json($rdata);
    }
	public function formdetail(){
		$id = input('param.id/d');
        $op = input('param.op');
        if($op == 'view' && (getcustom('form_log_plug') || cache($this->sessionid.'_formquery') == $id))
            $detail = Db::name('form_order')->where('aid',aid)->where('id',$id)->find();
        else
		    $detail = Db::name('form_order')->where('aid',aid)->where('mid',mid)->where('id',$id)->find();

        $detail['is_other_fee'] = 0;
        if(getcustom('form_other_money')){
            if($detail['fee_items']){
                $detail['is_other_fee'] = 1;
                $detail['fee_items'] = json_decode($detail['fee_items'],true);
            }
        }
		$detail['paytime'] = date('Y-m-d H:i:s',$detail['paytime']);
		$detail['createtime'] = date('Y-m-d H:i:s',$detail['createtime']);

		$form = Db::name('form')->where('aid',aid)->where('id',$detail['formid'])->find();
		$formcontent = json_decode($form['content'],true);

		$againname = '再次提交';
		if(getcustom('article_portion') ){

			//是否能编辑
			$detail['edit_status'] = false;
			if($form['edit_status'] == 1 && $detail['mid']==mid){
				$detail['edit_status'] = true;
			}

			$detail['edit_name'] = '编辑';
		}
		if(getcustom('businessindex_showfw')){
			$againname = '复制档案';
		}

		$rdata = [];
		$rdata['form'] = $form;
		$rdata['formcontent'] = $formcontent;
		$rdata['detail'] = $detail;
		$rdata['againname'] = $againname;
		return $this->json($rdata);

	}
	public function formdelete(){
		$id = input('param.id/d');
		Db::name('form_order')->where('aid',aid)->where('mid',mid)->where('id',$id)->update(['isudel'=>1]);
		return json(['status'=>1,'msg'=>'操作成功']);
	}
	public function favorite(){
		$pagenum = input('post.pagenum');
		if(!$pagenum) $pagenum = 1;
		$pernum = 20;
		$where = [];
		$where[] = ['aid','=',aid];
		$where[] = ['mid','=',mid];
		$datalist = Db::name('member_favorite')->field('id,proid,from_unixtime(createtime)createtime,type')->where($where)->page($pagenum,$pernum)->order('createtime desc')->select()->toArray();
		if(!$datalist) $datalist = [];
		foreach($datalist as $k=>$v){
			$product = [];
			if($v['type'] == 'shop'){
				$product = Db::name('shop_product')->where('id',$v['proid'])->find();
			}elseif($v['type'] == 'yuyue'){
				$product = Db::name('yuyue_product')->where('id',$v['proid'])->find();
			}elseif($v['type'] == 'seckill'){
				$product = Db::name('seckill_product')->where('id',$v['proid'])->find();
			}elseif($v['type'] == 'collage'){
				$product = Db::name('collage_product')->where('id',$v['proid'])->find();
			}elseif($v['type'] == 'scoreshop'){
				$product = Db::name('scoreshop_product')->where('id',$v['proid'])->find();
			}elseif($v['type'] == 'choujiang'){
				$product = Db::name('choujiang_product')->where('id',$v['proid'])->find();
				$product['market_price'] = $product['sell_price'];
				$product['sell_price'] = $product['min_price'];
			}elseif($v['type'] == 'kecheng'){
				$product = Db::name('kecheng_list')->where('id',$v['proid'])->find();
			}elseif($v['type'] == 'luckycollage'){
				$product = Db::name('lucky_collage_product')->where('id',$v['proid'])->find();
			}elseif($v['type'] == 'zhaopin'){
                $product = Db::name('zhaopin')->where('id',$v['proid'])->find();
            }elseif($v['type'] == 'qiuzhi'){
                $product = Db::name('zhaopin_qiuzhi')->where('id',$v['proid'])->find();
            }elseif($v['type'] == 'yueke'){
                $product = Db::name('yueke_product')->where('id',$v['proid'])->find();
            } elseif($v['type'] == 'cycle'){
                $product = Db::name('cycle_product')->where('id',$v['proid'])->find();
            }
			if(!$product){
				Db::name('member_favorite')->where('id',$v['id'])->delete();
				unset($datalist[$k]);
			}else{
				$datalist[$k]['product'] = $product;
			}
		}
		if(request()->isPost()){
			return $this->json(['status'=>1,'data'=>$datalist]);
		}
		$count = Db::name('member_favorite')->where($where)->count();

		$rdata = [];
		$rdata['count'] = $count;
		$rdata['datalist'] = $datalist;
		$rdata['pernum'] = $pernum;
		return $this->json($rdata);
	}
	public function favoritedel(){
		$post = input('post.');
		Db::name('member_favorite')->where('aid',aid)->where('mid',mid)->where('id',$post['id'])->delete();
		return $this->json(['status'=>1,'msg'=>'已取消','url'=>true]);
	}

	public function history(){
		$pagenum = input('post.pagenum');
		if(!$pagenum) $pagenum = 1;
		$pernum = 20;
		$where = [];
		$where[] = ['aid','=',aid];
		$where[] = ['mid','=',mid];
		$datalist = Db::name('member_history')->field('id,proid,from_unixtime(createtime)createtime,type')->where($where)->page($pagenum,$pernum)->order('createtime desc')->select()->toArray();
		if(!$datalist) $datalist = [];
		foreach($datalist as $k=>$v){
			$product = [];
			if($v['type'] == 'shop'){
				$product = Db::name('shop_product')->where('id',$v['proid'])->find();
			}elseif($v['type'] == 'yuyue'){
				$product = Db::name('yuyue_product')->where('id',$v['proid'])->find();
			}elseif($v['type'] == 'collage'){
				$product = Db::name('collage_product')->where('id',$v['proid'])->find();
			}elseif($v['type'] == 'scoreshop'){
				$product = Db::name('scoreshop_product')->where('id',$v['proid'])->find();
			}elseif($v['type'] == 'choujiang'){
				$product = Db::name('choujiang_product')->where('id',$v['proid'])->find();
				$product['market_price'] = $product['sell_price'];
				$product['sell_price'] = $product['min_price'];
			}elseif($v['type'] == 'zhaopin'){
                $product = Db::name('zhaopin')->where('id',$v['proid'])->find();
            }elseif($v['type'] == 'qiuzhi'){
                $product = Db::name('zhaopin_qiuzhi')->where('id',$v['proid'])->find();
            }
			if(!$product){
				Db::name('member_history')->where('id',$v['id'])->delete();
				unset($datalist[$k]);
			}else{
				$datalist[$k]['product'] = $product;
			}
		}
		if(request()->isPost()){
			return $this->json(['status'=>1,'data'=>$datalist]);
		}
		$count = Db::name('member_history')->where($where)->count();

		$rdata = [];
		$rdata['count'] = $count;
		$rdata['datalist'] = $datalist;
		$rdata['pernum'] = $pernum;
		return $this->json($rdata);
	}
	public function historydel(){
		$post = input('post.');
		if($post['proid'] =='all'){
			$rs = Db::name('member_history')->where('aid',aid)->where('mid',mid)->delete();
		}else{
			$rs = Db::name('member_history')->where('aid',aid)->where('mid',mid)->where('proid',$post['proid'])->where('type',$post['type'])->delete();
		}
		return $this->json(['status'=>1,'msg'=>'已删除','url'=>true]);
	}
	//等级说明
	public function levelinfo(){
        $id = input('param.id/d', $this->member['levelid']);
        if(empty($id)) $id = $this->member['levelid'];
		$userinfo = Db::name('member')->where('id',mid)->field('id,nickname,headimg,sex,levelid,levelendtime,areafenhong,areafenhongbl,areafenhong_province province,areafenhong_city city,areafenhong_area area,areafenhong_largearea largearea')->find();
		if($id != $this->member['levelid']) {
            $levelids = Db::name('member_level_record')->where('aid', aid)->where('mid',mid)->column('levelid');
            if(!in_array($id,$levelids)) {
                return $this->json(['status'=>0,'msg'=>'不存在的等级','url'=>true]);
            }
        }

		$userlevel = Db::name('member_level')->where('id',$id)->find();
		if($userinfo['areafenhong'] == 1) $userlevel['areafenhong'] = 1;
		if($userinfo['areafenhong'] == 2) $userlevel['areafenhong'] = 2;
		if($userinfo['areafenhong'] == 3) $userlevel['areafenhong'] = 3;
		if($userinfo['areafenhong'] == 4) $userlevel['areafenhong'] = 0;
		if($userlevel){
			$nextlevel = Db::name('member_level')->where("`sort`>{$userlevel['sort']} or (`sort`={$userlevel['sort']} and id>{$userlevel['id']})")->where('cid', $userlevel['cid'])->find();
		}
		if($nextlevel){
			$hasnext = 1;
		}else{
			$hasnext = 0;
		}
		$rdata = [];
		$rdata['userinfo'] = $userinfo;
		$rdata['userlevel'] = $userlevel;
		$rdata['hasnext'] = $hasnext;
		return $this->json($rdata);
	}
	//升级
	public function levelup(){
		if(request()->isPost()){
			$post = input('post.');
			$formdata = $post;
			if(!$this->member){
				return $this->json(['status'=>0,'msg'=>'参数错误,请重新操作']);
			}
			$this->member['ordercount'] = 0 + Db::name('shop_order')->where('aid',aid)->where('mid',mid)->where('status',3)->count();
			$this->member['ordermoney'] = 0 + Db::name('shop_order')->where('aid',aid)->where('mid',mid)->where('status',3)->sum('totalprice');
			$this->member['rechargemoney'] = 0 + Db::name('recharge_order')->where('aid',aid)->where('mid',mid)->where('status',1)->sum('money');

			$leveldata = Db::name('member_level')->where('aid',aid)->where('id',$formdata['levelid'])->find();
			if(!$leveldata['apply_paytxt']) $leveldata['apply_paytxt'] = '升级费用';
			//dump($formdata);
			if(!$leveldata){
				return $this->json(['status'=>0,'msg'=>'参数错误,请重新操作!']);
			}
			$canapply = 0;
			if($leveldata['apply_ordermoney'] <= 0 && $leveldata['apply_rechargemoney'] <= 0){
				$canapply = 1;
			}
			if ($leveldata['apply_ordermoney']>0 && $this->member['ordermoney'] >= $leveldata['apply_ordermoney']){
				$canapply = 1;
			}
			if ($leveldata['apply_rechargemoney']>0 && $this->member['rechargemoney'] >= $leveldata['apply_rechargemoney']){
				$canapply = 1;
			}
            $data = [];
            $data['aid'] = aid;
            $data['mid'] = mid;
			if(getcustom('levelup_code')){
                $code = $formdata['code']?trim($formdata['code']):'';
                if($code){
                	if($leveldata['can_apply'] != 1){
                		return $this->json(['status'=>0,'msg'=>'此等级申请功能暂未开启']);
                	}else{
                		if($code != $leveldata['apply_code']){
	                        return $this->json(['status'=>0,'msg'=>'验证码错误']);
	                    }else{
	                        $canapply = 1;
	                    }
                	}
                }
                if(getcustom('school_product')){
                    $data['school_id'] = input('post.school_id/d',0);
                    $data['grade_id'] = input('post.grade_id/d',0);
                    $data['class_id'] = input('post.class_id/d',0);
                }
            }
			if(!$canapply){
				return $this->json(['status'=>0,'msg'=>'不满足申请条件']);
			}

			//是否有待审核的记录
			$hasds = Db::name('member_levelup_order')->where('aid',aid)->where('mid',mid)->where('levelid',$leveldata['id'])->where('status',1)->find();
			if($hasds){
				return $this->json(['status'=>0,'msg'=>'您已经提交过了,请等待审核']);
			}
			if(getcustom('plug_xiongmao')){
				$hasds = Db::name('member_levelup_order')->where('aid',aid)->where('mid',mid)->find();
				if($hasds){
					return $this->json(['status'=>0,'msg'=>'您已经提交过了']);
				}
			}

			if($leveldata['maxnum'] > 0){
				$hascount = Db::name('member')->where('aid',aid)->where('levelid',$leveldata['id'])->count();
				if($hascount >= $leveldata['maxnum']) return $this->json(['status'=>0,'msg'=>'该等级申请名额已满']);
			}

			$return = [];
			$data['levelid'] = $leveldata['id'];
			$data['beforelevelid'] = $this->member['levelid'];

			$ordernum = date('ymdHis').aid.rand(1000,9999);
			$data['ordernum'] = $ordernum;
			$data['title'] = '升级成为'.$leveldata['name'];

			$apply_formdata = json_decode($leveldata['apply_formdata'],true);

			foreach($apply_formdata as $k=>$v){
				$value = $formdata['form'.$k];
				if(is_array($value)){
					$value = implode(',',$value);
				}
				$value = strval($value);
				$data['form'.$k] = $v['val1'] . '^_^' .$value . '^_^' .$v['key'];
				if($v['val3']==1 && $value===''){
					return $this->json(['status'=>0,'msg'=>$v['val1'].' 必填']);
				}
				if($v['key']=='region' && getcustom('buy_selectmember')){
					$region = explode(',',$value);
					Db::name('member')->where('aid',aid)->where('id',mid)->update(['province'=>$region[0],'city'=>$region[1],'area'=>$region[2]]);
				}
			}
			if(getcustom('plug_xiongmao')){
				Db::name('member')->where('id',mid)->update(['realname'=>explode('^_^',$data['form0'])[1],'tel'=>explode('^_^',$data['form1'])[1]]);
			}
			if($leveldata['areafenhong']==1){
				$data['areafenhong_province'] = $post['areafenhong_province'];
				if($leveldata['areafenhongmaxnum'] > 0){
					$hascount = Db::name('member')->where('aid',aid)->where('levelid',$leveldata['id'])->where('areafenhong_province',$data['areafenhong_province'])->count();
					if($hascount >= $leveldata['areafenhongmaxnum']) return $this->json(['status'=>0,'msg'=>'该区域名额已满']);
				}
			}elseif($leveldata['areafenhong']==2){
				$data['areafenhong_province'] = $post['areafenhong_province'];
				$data['areafenhong_city'] = $post['areafenhong_city'];
				if($leveldata['areafenhongmaxnum'] > 0){
					$hascount = Db::name('member')->where('aid',aid)->where('levelid',$leveldata['id'])->where('areafenhong_province',$data['areafenhong_province'])->where('areafenhong_city',$data['areafenhong_city'])->count();
					if($hascount >= $leveldata['areafenhongmaxnum']) return $this->json(['status'=>0,'msg'=>'该区域名额已满']);
				}
			}elseif($leveldata['areafenhong']==3){
				$data['areafenhong_province'] = $post['areafenhong_province'];
				$data['areafenhong_city'] = $post['areafenhong_city'];
				$data['areafenhong_area'] = $post['areafenhong_area'];
				if($leveldata['areafenhongmaxnum'] > 0){
					$hascount = Db::name('member')->where('aid',aid)->where('levelid',$leveldata['id'])->where('areafenhong_province',$data['areafenhong_province'])->where('areafenhong_city',$data['areafenhong_city'])->where('areafenhong_area',$data['areafenhong_area'])->count();
					if($hascount >= $leveldata['areafenhongmaxnum']) return $this->json(['status'=>0,'msg'=>'该区域名额已满']);
				}
			}elseif($leveldata['areafenhong']==10){
				$data['areafenhong_largearea'] = $post['areafenhong_largearea'];
				if($leveldata['areafenhongmaxnum'] > 0){
					$hascount = Db::name('member')->where('aid',aid)->where('levelid',$leveldata['id'])->where('areafenhong_largearea',$data['areafenhong_largearea'])->count();
					if($hascount >= $leveldata['areafenhongmaxnum']) return $this->json(['status'=>0,'msg'=>'该区域名额已满']);
				}
			}

			$data['totalprice'] = $leveldata['apply_paymoney'];
			$data['createtime'] = time();
			if($leveldata['apply_paymoney'] > 0){
				$data['status'] = 0;
				$orderid = Db::name('member_levelup_order')->insertGetId($data);
				$payorderid = \app\model\Payorder::createorder(aid,0,$data['mid'],'member_levelup',$orderid,$data['ordernum'],$data['title'],$data['totalprice']);
				$return = ['status'=>1,'msg'=>'提交成功，正在跳转到支付','url'=>'/pages/pay/pay?id='.$payorderid];
			}else{
				$data['status'] = 1;
				$orderid = Db::name('member_levelup_order')->insertGetId($data);

				if($leveldata['apply_check']){
					$return = ['status'=>1,'msg'=>'提交成功请等待审核','url'=>'/pages/my/usercenter'];

					$tmplcontent = [];
					$tmplcontent['first'] = '有新用户申请升级,请及时处理';
					$tmplcontent['remark'] = '请进入电脑端后台进行审核~';
					$tmplcontent['keyword1'] = $leveldata['name']; //会员等级
					$tmplcontent['keyword2'] = '待审核';//审核状态
					\app\common\Wechat::sendhttmpl(aid,0,'tmpl_uplv',$tmplcontent);
				}else{
					if($leveldata['yxqdate'] > 0){
						$levelendtime = strtotime(date('Y-m-d')) + 86400 + 86400 * $leveldata['yxqdate'];
					}else{
						$levelendtime = 0;
					}
					//判断是否默认分组
					if($leveldata['cid'] > 0)
                    $is_default = Db::name('member_level_category')->where('id', $leveldata['cid'])->value('isdefault');
					if($is_default == 1 || $leveldata['cid'] == 0) {
                        Db::name('member')->where('aid',aid)->where('id',mid)->update(['levelid'=>$leveldata['id'],'levelendtime'=>$levelendtime]);
                        if(getcustom('level_comwithdraw')){
                            if($this->member['levelstarttime']<=0 && $leveldata['fenhong'] > 0){
                                Db::name('member')->where('aid',aid)->where('id',mid)->update(['levelstarttime'=>time()]);
                            }
                        }else{
                            Db::name('member')->where('aid',aid)->where('id',mid)->update(['levelstarttime'=>time()]);
                        }
                        //0702加--更新上级拉新时间
                        $memberc = Db::name('member')->where('aid',aid)->where('id',mid)->find();
                        Db::name('member')->where('aid',aid)->where('id',$memberc['pid'])->update(['laxin_time'=>time()]);

                        //更新代理区域
                        if($leveldata['areafenhong']==1){
                            Db::name('member')->where('aid',aid)->where('id',mid)->update(['areafenhong_province'=>$post['areafenhong_province']]);
                        }elseif($leveldata['areafenhong']==2){
                            Db::name('member')->where('aid',aid)->where('id',mid)->update(['areafenhong_province'=>$post['areafenhong_province'],'areafenhong_city'=>$post['areafenhong_city']]);
                        }elseif($leveldata['areafenhong']==3){
                            Db::name('member')->where('aid',aid)->where('id',mid)->update(['areafenhong_province'=>$post['areafenhong_province'],'areafenhong_city'=>$post['areafenhong_city'],'areafenhong_area'=>$post['areafenhong_area']]);
                        }elseif($leveldata['areafenhong']==10){
                            Db::name('member')->where('aid',aid)->where('id',mid)->update(['areafenhong_largearea'=>$post['areafenhong_largearea']]);
                        }
                    } else {
					    if(getcustom('plug_sanyang')) {
					        Db::name('member_level_record')->where('aid',aid)->where('mid',mid)->where('cid', $leveldata['cid'])->update(['levelid'=>$leveldata['id'],'levelendtime'=>$levelendtime]);
                            if(getcustom('level_comwithdraw')){
                                if($this->member['levelstarttime']<=0 && $leveldata['fenhong'] > 0){
                                    Db::name('member_level_record')->where('aid',aid)->where('mid',mid)->where('cid', $leveldata['cid'])->update(['levelstarttime'=>time()]);
                                }
                            }else{
                                Db::name('member_level_record')->where('aid',aid)->where('mid',mid)->where('cid', $leveldata['cid'])->update(['levelstarttime'=>time()]);
                            }
                            //0702加--更新上级拉新时间
                            $memberc = Db::name('member')->where('aid',aid)->where('id',mid)->find();
                            Db::name('member')->where('aid',aid)->where('id',$memberc['pid'])->update(['laxin_time'=>time()]);

                            //更新代理区域
                            if($leveldata['areafenhong']==1){
                                Db::name('member_level_record')->where('aid',aid)->where('mid',mid)->where('cid', $leveldata['cid'])->update(['areafenhong_province'=>$post['areafenhong_province']]);
                            }elseif($leveldata['areafenhong']==2){
                                Db::name('member_level_record')->where('aid',aid)->where('mid',mid)->where('cid', $leveldata['cid'])->update(['areafenhong_province'=>$post['areafenhong_province'],'areafenhong_city'=>$post['areafenhong_city']]);
                            }elseif($leveldata['areafenhong']==3){
                                Db::name('member_level_record')->where('aid',aid)->where('mid',mid)->where('cid', $leveldata['cid'])->update(['areafenhong_province'=>$post['areafenhong_province'],'areafenhong_city'=>$post['areafenhong_city'],'areafenhong_area'=>$post['areafenhong_area']]);
                            }
                        }
                    }

					Db::name('member_levelup_order')->where('id',$orderid)->update(['status'=>2,'paytime'=>time()]);
					$return = ['status'=>1,'msg'=>'申请成功','url'=>'/pages/my/usercenter'];

                    //赠送积分
                    if($leveldata['up_give_score'] > 0) {
                        \app\common\Member::addscore(aid,mid,$leveldata['up_give_score'],'升级奖励');
                    }
                    //奖励佣金
                    if($leveldata['up_give_commission'] > 0) {
                        \app\common\Member::addcommission(aid,mid,0,$leveldata['up_give_commission'],'升级奖励');
                    }
                    //奖励余额
                    if($leveldata['up_give_money'] > 0) {
                        \app\common\Member::addmoney(aid,mid,$leveldata['up_give_money'],'升级奖励');
                    }

                    //赠送上级佣金
                    if ($leveldata['up_give_parent_money'] > 0 && $this->member['pid']) {
                        \app\common\Member::addcommission(aid, $this->member['pid'], mid, $leveldata['up_give_parent_money'], '下级升级赠送');
                    }

					$tmplcontent = [];
					$tmplcontent['first'] = '恭喜您成功升级为'.$leveldata['name'];
					$tmplcontent['remark'] = '点击进入查看~';
					$tmplcontent['keyword1'] = $leveldata['name']; //会员等级
					$tmplcontent['keyword2'] = '已生效';//审核状态
					$rs = \app\common\Wechat::sendtmpl(aid,mid,'tmpl_uplv',$tmplcontent,m_url('pages/my/usercenter'));
				}
			}
			$return['orderid'] = $orderid;
			return $this->json($return);
		}
		$member = Db::name('member')->field('realname,tel,weixin,aliaccount,bankcardnum,bankname,bankcarduser,levelid')->where('aid',aid)->where('id',mid)->find();

		$member['ordermoney'] = Db::name('shop_order')->where('aid',aid)->where('mid',mid)->where('status',3)->sum('totalprice');
		$member['rechargemoney'] = Db::name('recharge_order')->where('aid',aid)->where('mid',mid)->where('status',1)->sum('money');

        $id = input('param.id/d');//传id为其他分组等级升级
        $cid = input('param.cid/d');//传cid为指定分组升级，

        if($cid && !$id) {
            $level_record = Db::name('member_level_record')->where('aid',aid)->where('mid', mid)->where('cid', $cid)->find();
            if(!empty($level_record)) {
                $id = $level_record['levelid'];
            }
        }
		if(!$id) $id = $member['levelid'];
		//我的等级
		$mylevel = Db::name('member_level')->where('aid',aid)->where('id',$id)->find();
		$member['levelid'] = $mylevel['id'];
		//等级列
		$where = [];
		$where[] = ['aid','=',aid];
		//如果可跨级 则允许展示所有等级 如果不允许跨级 则只能显示比当前等级高的
        $skip_level = 0;
        if(getcustom('skip_levelup')){
            $skip_level = Db::name('member_level_bgset')->where('aid',aid)->value('skip_level');
        }
        if($skip_level==1){
            //不等于当前等级
//            $where[] = ['id','<>',$mylevel['id']];
        }else{
            $where[] = ['sort','>',$mylevel['sort']];
        }
		if(getcustom('levelup_code')){
			$levelid =  input('param.levelid')?input('param.levelid/d'):0;//等级id
			if($levelid>0){
				$where[] = ['id','=',$levelid];
			}
			$ycode =  input('param.ycode');//验证码
			if(isset($ycode)){
				$ycode = trim($ycode);
				if($ycode){
					$where[] = ['apply_code','=',$ycode];
					$where[] = ['can_apply','=',1];
				}else{
					$where[] = ['id','=',-1];
				}
			}else{
				$where[] = Db::raw("can_apply=1 || (can_up=1 && (up_wxpaymoney>0 || up_ordermoney>0 || up_rechargemoney>0 || up_getmembercard>0 || up_fxordermoney>0 || up_fxdowncount>0 || up_proid>0))");
			}
		}else{
			$where[] = Db::raw("can_apply=1 || (can_up=1 && (up_wxpaymoney>0 || up_ordermoney>0 || up_rechargemoney>0 || up_getmembercard>0 || up_fxordermoney>0 || up_fxdowncount>0 || up_proid>0))");
		}
		$aglevelList = Db::name('member_level')->where($where)->where('cid', $cid ? $cid : $mylevel['cid'])->order('sort')->select()->toArray();
		if(!$aglevelList) $aglevelList = [];
		foreach($aglevelList as $k=>$lv){
			if(getcustom('levelup_code')){
				$aglevelList[$k]['applycode']  = '';//增加一个额外的参数
				$aglevelList[$k]['apply_code'] = $aglevelList[$k]['apply_code']?true:false;//去掉验证码数据
			}
			if($lv['up_proid']){
                $aglevelList[$k]['up_proname'] = '';
			    $up_proid = explode(',', $lv['up_proid']);
                $up_pronum = explode(',', $lv['up_pronum']);
                if($up_proid)
				    $up_pro = Db::name('shop_product')->whereIn('id',$up_proid)->field('name')->select()->toArray();
                if($up_pro) {
                    foreach ($up_pro as $pk => $pro) {
                        if($pro['name'] && $up_pronum[$pk]) {
                            if($pk) {
                                $aglevelList[$k]['up_proname'] .= ' + ';
                            }
                            $aglevelList[$k]['up_proname'] .= $pro['name'].'x'.$up_pronum[$pk];
                        }
                    }
                }
			}
            $atj = array();
			//申请
            $aglevelList[$k]['applytj_reach'] = 0;
            $aglevelList[$k]['applytj'] = '';
            if($lv['can_apply'] == 1){
                if (empty($lv['apply_ordermoney'])) $lv['apply_ordermoney'] = 0;
                if (empty($lv['apply_rechargemoney'])) $lv['apply_rechargemoney'] = 0;
                if ($lv['apply_ordermoney'] <= 0 && $lv['apply_rechargemoney'] <= 0) {
                    $aglevelList[$k]['applytj_reach'] = 1;
                }
                if($lv['apply_ordermoney'] > 0) {
                    $atj[]='累计订单金额满'.$lv['apply_ordermoney'].'元';
                    if($member['ordermoney'] >= $lv['apply_ordermoney']) {
                        $aglevelList[$k]['applytj_reach'] = 1;
                    }
                }
                if($lv['apply_rechargemoney'] > 0) {
                    $atj[]='累计充值金额满'.$lv['apply_rechargemoney'].'元';
                    if($member['rechargemoney'] >= $lv['apply_rechargemoney']) {
                        $aglevelList[$k]['applytj_reach'] = 1;
                    }
                }
                if($atj){
                    $aglevelList[$k]['applytj'] = implode(' 或 ',$atj);
                }
            }
            //升级
            if($lv['can_up'] == 1 && $lv['up_condition_show'] == 1){
                $tj = array();
                $must = array();
                //if($lv['up_ordercount'] > 0) $tj[]='订单满'.$lv['up_ordercount'].'个';
                if($lv['up_wxpaymoney'] > 0) $tj['up_wxpaymoney']='微信支付金额满'.$lv['up_wxpaymoney'].'元';
                if($lv['up_ordermoney'] > 0) $tj['up_ordermoney']='订单金额满'.$lv['up_ordermoney'].'元';
                if($lv['up_rechargemoney'] > 0) $tj['up_rechargemoney']='充值金额满'.$lv['up_rechargemoney'].'元';
                if($lv['up_fxordermoney'] > 0) $tj['up_fxordermoney']='分销订单满'.$lv['up_fxordermoney'].'元';
                if($lv['up_fxdowncount'] > 0) {
                    $up_fxdownlevelnum = '';
                    $levelnameStr = '';
                    if($lv['up_fxdownlevelnum'] > 0) {
                        $up_fxdownlevelnum = $lv['up_fxdownlevelnum'];
                    }
                    if(!empty($lv['up_fxdownlevelid'])) {
                        $levelNames = Db::name('member_level')->where('aid', aid)->where('id', 'in', $lv['up_fxdownlevelid'])->column('name');
                        $levelnameStr = '['.implode(',',$levelNames).']';
                    }
                    if($lv['up_fxorder_condition'] == 'and')
                        $must['up_fxdowncount']='下'.$up_fxdownlevelnum.'级'.$levelnameStr.'总人数满'.$lv['up_fxdowncount'].'个';
                    else
                        $tj['up_fxdowncount']='下'.$up_fxdownlevelnum.'级'.$levelnameStr.'总人数满'.$lv['up_fxdowncount'].'个';
                }
                if($lv['up_fxdowncount2'] > 0) {
                    $up_fxdownlevelnum = '';
                    $levelnameStr = '';
                    if($lv['up_fxdownlevelnum2'] > 0) {
                        $up_fxdownlevelnum = $lv['up_fxdownlevelnum2'];
                    }
                    if(!empty($lv['up_fxdownlevelid2'])) {
                        $levelNames = Db::name('member_level')->where('aid', aid)->where('id', 'in', $lv['up_fxdownlevelid2'])->column('name');
                        $levelnameStr = '['.implode(',',$levelNames).']';
                    }
                    if($lv['up_fxorder_condition'] == 'and')
                        $must['up_fxdowncount'].=' 且 下'.$up_fxdownlevelnum.'级'.$levelnameStr.'总人数满'.$lv['up_fxdowncount2'].'个';
                    else
                        $tj['up_fxdowncount'].=' 且 下'.$up_fxdownlevelnum.'级'.$levelnameStr.'总人数满'.$lv['up_fxdowncount2'].'个';
                }
                if($lv['up_fxdowncount3'] > 0) {
                    $up_fxdownlevelnum = '';
                    $levelnameStr = '';
                    if($lv['up_fxdownlevelnum3'] > 0) {
                        $up_fxdownlevelnum = $lv['up_fxdownlevelnum3'];
                    }
                    if(!empty($lv['up_fxdownlevelid3'])) {
                        $levelNames = Db::name('member_level')->where('aid', aid)->where('id', 'in', $lv['up_fxdownlevelid3'])->column('name');
                        $levelnameStr = '['.implode(',',$levelNames).']';
                    }
                    if($lv['up_fxorder_condition'] == 'and')
                        $must['up_fxdowncount'].=' 且 下'.$up_fxdownlevelnum.'级'.$levelnameStr.'总人数满'.$lv['up_fxdowncount3'].'个';
                    else
                        $tj['up_fxdowncount'].=' 且 下'.$up_fxdownlevelnum.'级'.$levelnameStr.'总人数满'.$lv['up_fxdowncount3'].'个';
                }
//                if($lv['up_fxdowncount2'] > 0 || $lv['up_fxdowncount3'] > 0) {
//                    $tj['up_fxdowncount'] = '（'.$tj['up_fxdowncount'].'）';
//                }
                if($lv['up_fxdowncount_and'] > 0) {
                    $up_fxdownlevelnum = '';
                    $levelnameStr = '';
                    if($lv['up_fxdownlevelnum_and'] > 0) {
                        $up_fxdownlevelnum = $lv['up_fxdownlevelnum_and'];
                    }
                    if(!empty($lv['up_fxdownlevelid_and'])) {
                        $levelNames = Db::name('member_level')->where('aid', aid)->where('id', 'in', $lv['up_fxdownlevelid_and'])->column('name');
                        $levelnameStr = '['.implode(',',$levelNames).']';
                    }
                    $must['up_fxdowncount_and']='下'.$up_fxdownlevelnum.'级'.$levelnameStr.'总人数满'.$lv['up_fxdowncount_and'].'个';
                }
                if($lv['up_fxdowncount2_and'] > 0) {
                    $up_fxdownlevelnum = '';
                    $levelnameStr = '';
                    if($lv['up_fxdownlevelnum2_and'] > 0) {
                        $up_fxdownlevelnum = $lv['up_fxdownlevelnum2_and'];
                    }
                    if(!empty($lv['up_fxdownlevelid2_and'])) {
                        $levelNames = Db::name('member_level')->where('aid', aid)->where('id', 'in', $lv['up_fxdownlevelid2_and'])->column('name');
                        $levelnameStr = '['.implode(',',$levelNames).']';
                    }
                    $must['up_fxdowncount_and'].=' 且 下'.$up_fxdownlevelnum.'级'.$levelnameStr.'总人数满'.$lv['up_fxdowncount2_and'].'个';
                }
//                if($lv['up_fxdowncount2_and'] > 0) {
//                    $tj['up_fxdowncount_and'] = '（'.$tj['up_fxdowncount_and'].'）';
//                }
                if($lv['up_proid'] && $lv['up_pronum']) {
                    $proids = explode(',',$lv['up_proid']);
                    $numArr = explode(',',$lv['up_pronum']);
                    $products = Db::name('shop_product')->whereIn('id',$proids)->column('name');
                    if(count($products) > 1 && count($numArr) > 1) {
                        $tj['up_proid'] .='购买商品';
                        foreach($products as $key => $proname) {
                            $tj['up_proid'].='['.$proname.']*'.$numArr[$key].' ';
                        }
                    } elseif(count($products) > 1 && count($numArr) ==1) {
                        $tj['up_proid'] .='购买商品';
                        foreach($products as $key => $proname) {
                            $tj['up_proid'] .='['.$proname.']';
                        }
                        $tj['up_proid'] .= '累计满'.$numArr[0].'件';
                    } else {
                        $tj['up_proid']='购买商品['.$products[0].']*'.$numArr[0];
                    }
                }
                if($lv['up_getmembercard']==1) $tj[]='领取微信会员卡';
//                dd($tj);
//                if($tj){
//                    $i = 1;
//                    $aglevelList[$k]['uptj'] = '';
//                    foreach($tj as $key => $item) {
//                        if($i == 1) {
//                            $aglevelList[$k]['autouptj'] .= $item;
//                        } else {
//                            $realtion = ' 或 ';
//                            if($lv['up_fxorder_condition'] == 'and' && $key == 'up_fxordermoney') {
//                                $realtion = ' 且 ';
//                            }
//                            if($key == 'up_fxdowncount_and') {
//                                $realtion = ' 且 ';
//                            }
//                            $aglevelList[$k]['autouptj'] .= $realtion.$item;
//                        }
//                        $i++;
//                    }
//                }
                if($must){
                    $i = 1;
                    $aglevelList[$k]['uptj'] = '';
                    foreach($must as $key => $item)
                    {
                        $aglevelList[$k]['autouptj'] .= $i.'.'.$item."<br>";
                        $i++;
                    }
                }
                if($tj){
                    $i = count($must)+1;
                    $aglevelList[$k]['uptj'] = '';
                    $aglevelList[$k]['autouptj'] .= "<p style='color: #333;margin: 10px 0 5px;'>以下条件任意满足一个即可</p>";
                    foreach($tj as $key => $item)
                    {
                        $aglevelList[$k]['autouptj'] .= $i.'.'.$item."<br>";
                        $i++;
                    }
                }
            }

			$aglevelList[$k]['apply_formdata'] = json_decode($lv['apply_formdata'],true);
			if(!$aglevelList[$k]['apply_paytxt']) $aglevelList[$k]['apply_paytxt'] = '升级费用';
		}
		$set = Db::name('admin_set')->where('aid',aid)->field('name,logo,desc,banner_levelup')->find();
		
		$rdata = [];
		$rdata['sysset'] = $set;
		$rdata['userinfo'] = $member;
		$rdata['aglevelList'] = $aglevelList;
		$rdata['userlevel'] = $mylevel;
		if(getcustom('areafenhong_jiaquan')){
			$largearea = Db::name('largearea')->where('aid',aid)->where('status',1)->order('sort desc,id')->column('name');
			$rdata['largearea'] = $largearea;
		}
		if(getcustom('levelup_code')){
			$rdata['levelupcode'] = true;
			$rdata['bgset'] = '';

			//查询背景设置
			$bgset = Db::name('member_level_bgset')->where('aid',aid)->find();
			if($bgset){
				$rdata['bgset'] = [
					'title'      => $bgset['title'],
					'level_name' => $bgset['level_name'],
					'bgcolor'    => $bgset['bgcolor'],
					'bgimg'      => $bgset['bgimg'],
				];
			}
			if(getcustom('school_product')){
			    if($ycode){
                    $need_school = Db::name('admin')->where('id',aid)->value('need_school');
                    if($need_school==1){
                        //查询该学校下面的班级
                        $school = Db::name('school')->where('aid',aid)->where('number',$ycode)->find();
                        if(empty($school)){
                            return $this->json(['status'=>0,'msg'=>'错误的学校编码']);
                        }
                        $gradelist = Db::name('school_class')->where('aid',aid)->where('sid',$school['id'])->where('pid',0)->select()->toArray();
                        foreach ($gradelist as $sk=>$sv){
                            $classlist = Db::name('school_class')->where('aid',aid)->where('sid',$school['id'])->where('pid',$sv['id'])->select()->toArray();
                            $gradelist[$sk]['classlist'] = $classlist??[];
                        }
                        $rdata['need_school'] = 1;
                        $rdata['school_id'] = $school['id'];
                        $rdata['gradelist'] = $gradelist;
                        return $this->json($rdata);
                    }
                }
            }
	    }
		return $this->json($rdata);
	}
	function getPayCommissionApplyOrder(){
		$post = input('post.');
		$order = Db::name('member_levelup_order')->field('title,totalprice,ordernum,id')->where('id',$post['orderid'])->where('aid',aid)->where('mid',mid)->find();
		if(!$order){
			return $this->json(['status'=>0,'msg'=>'该订单不存在']);
		}
		if($order['status']){
			return $this->json(['status'=>0,'msg'=>'该订单已支付']);
		}
		return $this->json(['status'=>1,'msg'=>'获取成功','orderinfo'=>$order]);
	}
	function payCommissionApplyOrder(){
		$post = input('post.');
		$order = Db::name('member_levelup_order')->where('id',$post['orderid'])->where('aid',aid)->where('mid',mid)->find();
		if(!$order){
			return $this->json(['status'=>0,'msg'=>'该订单不存在']);
		}
		if($order['status'] > 0){
			return $this->json(['status'=>0,'msg'=>'该订单已支付']);
		}
		$leveldata = Db::name('member_level')->where('aid',aid)->where('id',$order['levelid'])->find();

		$levelid = $leveldata['id'];

		if($order['totalprice'] <=0){
			Db::name('member_levelup_order')->where('id',$order['id'])->update(['status'=>1]);
			if($leveldata['apply_check']){
				Db::name('member')->where('aid',aid)->where('id',mid)->update(['realname'=>$order['realname'],'tel'=>$order['tel'],'weixin'=>$order['weixin'],'aliaccount'=>$order['aliaccount'],'bankcardnum'=>$order['bankcardnum'],'bankcarduser'=>$order['bankcarduser'],'bankname'=>$order['bankname']]);
				$return = ['status'=>2,'msg'=>'付款成功请等待审核'];
			}else{
				Db::name('member')->where('aid',aid)->where('id',mid)->update(['realname'=>$order['realname'],'tel'=>$order['tel'],'weixin'=>$order['weixin'],'aliaccount'=>$order['aliaccount'],'bankcardnum'=>$order['bankcardnum'],'bankcarduser'=>$order['bankcarduser'],'bankname'=>$order['bankname'],'levelid'=>$levelid]);
				Db::name('member_levelup_order')->where('id',$order['id'])->update(['status'=>2]);
				$return = ['status'=>3,'msg'=>'申请成功'];
			}
			return $return;
		}
		//余额支付
		if($post['typeid']==2){
			if($this->member['money'] < $order['totalprice']){
				return $this->json(['status'=>0,'msg'=>t('余额').'不足,请充值']);
			}
			Db::name('member_levelup_order')->where('id',$order['id'])->update(['paytype'=>t('余额').'支付','paytime'=>time(),'status'=>1]);
			//减去会员的余额
			\app\common\Member::addmoney(aid,mid,-$order['totalprice'],$order['title']);

			if($leveldata['apply_check']){
				Db::name('member')->where('aid',aid)->where('id',mid)->update(['realname'=>$order['realname'],'tel'=>$order['tel'],'weixin'=>$order['weixin'],'aliaccount'=>$order['aliaccount'],'bankcardnum'=>$order['bankcardnum'],'bankcarduser'=>$order['bankcarduser'],'bankname'=>$order['bankname']]);
				$return = ['status'=>2,'msg'=>'付款成功请等待审核'];
			}else{
				Db::name('member')->where('aid',aid)->where('id',mid)->update(['realname'=>$order['realname'],'tel'=>$order['tel'],'weixin'=>$order['weixin'],'aliaccount'=>$order['aliaccount'],'bankcardnum'=>$order['bankcardnum'],'bankcarduser'=>$order['bankcarduser'],'bankname'=>$order['bankname'],'levelid'=>$levelid]);
				Db::name('member_levelup_order')->where('id',$order['id'])->update(['status'=>2]);
				$return = ['status'=>3,'msg'=>'申请成功'];
			}
			return $return;
		}else{
			$rs = \app\common\Wxpay::build(aid,mid,$this->member['openid'],'升级['.$leveldata['name'].']',$order['ordernum'],$order['totalprice'],'member_levelup_order');
			$rs['apply_check'] = $leveldata['apply_check'];
			return $rs;
		}
	}
	//领卡回调
	public function usergetcard(){
		$post = input('post.');
		Log::write('领取会员卡---'.mid.'---'.print_r($post,true));
		$extraData = $post['extraData'];
		$code = $extraData['code'];
		$activate_ticket = $extraData['activate_ticket'];
		$card_id = $extraData['card_id'];
		if($this->member['activate_ticket'] && $this->member['activate_ticket'] == $activate_ticket){
			return $this->json(['status'=>1,'msg'=>'已开卡']);
		}
		$url = urldecode($extraData['wx_activate_after_submit_url']);
		$params =  explode('&',explode('?',$url)[1]);
		$mpopenid = '';
		foreach($params as $v){
			if($v!=''){
				$vArr = explode('=',$v);
				if($vArr[0] == 'openid'){
					$mpopenid = $vArr[1];
				}
			}
		}
		Log::write('公众号openid '.$mpopenid);

		$mdata = [];
		$mdata['mpopenid'] = $mpopenid;
		$mdata['card_id'] = $card_id;
		$mdata['card_code'] = $code;
		$mdata['activate_ticket'] = $activate_ticket;

		Db::name('member')->where('aid',aid)->where('id',mid)->update($mdata);
		return $this->json(['status'=>1,'msg'=>'开卡成功']);
		die;
		$access_token = access_token(aid,'mp');
		$url = 'https://api.weixin.qq.com/card/membercard/activatetempinfo/get?access_token='.$access_token;
		$rs = request_post($url,jsonEncode(['activate_ticket'=>$activate_ticket]));
		$rs = json_decode($rs,true);
		Log::write('获取领卡信息---'.mid.'---'.print_r($rs,true));
		if($rs['errcode'] == 0){
			if($rs['info']){
				foreach($rs['info']['common_field_list'] as $key=>$v){
					if($v['name'] == 'USER_FORM_INFO_FLAG_MOBILE'){
						$mdata['tel']=$v['value'];
					}
					if($v['name'] == 'USER_FORM_INFO_FLAG_NAME'){
						$mdata['realname']=$v['value'];
					}
					if($v['name'] == 'USER_FORM_INFO_FLAG_BIRTHDAY'){
						$mdata['birthday'] = $v['value'];
					}
					if($v['name'] == 'USER_FORM_INFO_FLAG_LOCATION'){
						$mdata['location']=$v['value'];
					}
					if($v['name'] == 'USER_FORM_INFO_FLAG_IDCARD'){
						$mdata['usercard']=$v['value'];
					}
				}
			}
		}else{
			Log::write('领卡时获取开卡的信息失败:'.$rs);
		}
	}

	//余额宝提现
	public function yuebao_withdraw(){
		if(!getcustom('plug_yuebao')) {
			die;
		}
		$set = Db::name('admin_set')
		     ->where('aid',aid)
		     ->field('open_yuebao,yuebao_withdraw_time,yuebao_withdraw,yuebao_withdrawmin,yuebao_withdrawfee,withdraw_autotransfer,withdraw_weixin,withdraw_aliaccount,withdraw_bankcard,yuebao_turn_yue')
		     ->find();
		if($set['open_yuebao'] == 0){
			return $this->json(['status'=>0,'msg'=>t('余额宝').'功能未开启']);
		}
		if(request()->isPost()){
			$post = input('post.');

			if($set['yuebao_withdraw'] == 0){
				return $this->json(['status'=>0,'msg'=>t('余额宝').'收益提现功能未开启']);
			}

			//查询上次提现、转余额时间
			$find_ytime = Db::name('member_yuebao_moneylog')
				->where('aid',aid)
				->where('mid',mid)
				->where('money','<',0)
				->where('type','>=',2)
				->where('type','<=',3)
				->field('createtime')
				->order('createtime desc')
				->find();
			if($find_ytime){
				//现在时间与上次时间差
				$cha = time()-$find_ytime['createtime'];

				//限制提现天数
				$wday  = 0;
				//限制提现秒数
				$wtime = 0;

				//如果单独设置天数
				if($this->member['yuebao_withdraw_time']>0){
					$wday = $this->member['yuebao_withdraw_time'];
					//转换天为秒
					$wtime = $this->member['yuebao_withdraw_time']*24*60*60;
				}else{
					//如果单独设置天数为负数，且总天数设置大于0
					if($this->member['yuebao_withdraw_time'] <0 && $set['yuebao_withdraw_time']>0){
						$wday = $set['yuebao_withdraw_time'];
						//转换天为秒
						$wtime = $set['yuebao_withdraw_time']*24*60*60;
					}
				}

				if($wtime>0 && $cha<$wtime){
					return $this->json(['status'=>0,'msg'=>t('余额宝').'收益'.$wday.'天可提现一次']);
				}

			}
			if($post['paytype']=='支付宝' && $this->member['aliaccount']==''){
				return $this->json(['status'=>0,'msg'=>'请先设置支付宝账号']);
			}
			if($post['paytype']=='银行卡' && ($this->member['bankname']==''||$this->member['bankcarduser']==''||$this->member['bankcardnum']=='')){
				return $this->json(['status'=>0,'msg'=>'请先设置完整银行卡信息']);
			}

			$money = $post['money'];
			if($money<=0 || $money < $set['yuebao_withdrawmin']){
				return $this->json(['status'=>0,'msg'=>'提现金额必须大于'.($set['yuebao_withdrawmin']?$set['yuebao_withdrawmin']:0)]);
			}
			if($money > $this->member['yuebao_money']){
				return $this->json(['status'=>0,'msg'=>'可提现'.t('余额宝').'收益不足']);
			}

			$ordernum = date('ymdHis').aid.rand(1000,9999);
			$record['aid'] = aid;
			$record['mid'] = mid;
			$record['createtime']= time();
			$record['money'] = $money*(1-$set['yuebao_withdrawfee']*0.01);
			if($record['money'] <= 0) {
                return $this->json(['status'=>0,'msg'=>'提现金额有误']);
            }
            $record['money'] = round($record['money'],2);
			$record['txmoney'] = $money;
			if($post['paytype']=='支付宝'){
				$record['aliaccountname'] = $this->member['aliaccountname'];
				$record['aliaccount'] = $this->member['aliaccount'];
			}
			if($post['paytype']=='银行卡'){
				$record['bankname'] = $this->member['bankname'] . ($this->member['bankaddress'] ? ' '.$this->member['bankaddress'] : '');
				$record['bankcarduser'] = $this->member['bankcarduser'];
				$record['bankcardnum'] = $this->member['bankcardnum'];
			}
			$record['ordernum'] = $ordernum;
			$record['paytype']  = $post['paytype'];
			$record['platform'] = platform;
			$recordid = Db::name('member_yuebao_withdrawlog')->insertGetId($record);

			\app\common\Member::addyuebaomoney(aid,mid,-$money,t('余额宝').'收益提现',2);

			if($post['paytype'] != ''){
				$tmplcontent = array();
				$tmplcontent['first'] = '有客户申请'.t('余额宝').'收益提现';
				$tmplcontent['remark'] = '点击进入查看~';
				$tmplcontent['keyword1'] = $this->member['nickname'];
				$tmplcontent['keyword2'] = date('Y-m-d H:i');
				$tmplcontent['keyword3'] = $money.'元';
				$tmplcontent['keyword4'] = $post['paytype'];
				\app\common\Wechat::sendhttmpl(aid,0,'tmpl_withdraw',$tmplcontent,m_url('admin/finance/yuebaowithdrawlog'));
				
				$tmplcontent = [];
				$tmplcontent['name3'] = $this->member['nickname'];
				$tmplcontent['amount1'] = $money.'元';
				$tmplcontent['date2'] = date('Y-m-d H:i');
				$tmplcontent['thing4'] = '提现到'.$post['paytype'];
				\app\common\Wechat::sendhtwxtmpl(aid,0,'tmpl_withdraw',$tmplcontent,'admin/finance/yuebaowithdrawlog');
			}

			if($set['withdraw_autotransfer'] && ($post['paytype'] = '微信钱包' || $post['paytype'] = '银行卡')){
                Db::name('member_yuebao_withdrawlog')->where('id',$recordid)->update(['status' => 1]);
				$rs = \app\common\Wxpay::transfers(aid,mid,$record['money'],$record['ordernum'],platform,t('余额宝').'收益提现');
				if($rs['status']==0){
					return json(['status'=>1,'msg'=>'提交成功,请等待打款']);
				}else{
                    Db::name('member_yuebao_withdrawlog')->where('id',$recordid)->update(['status' => 3]);
					Db::name('member_yuebao_withdrawlog')->where('aid',aid)->where('id',$recordid)->update(['status'=>3,'paytime'=>time(),'paynum'=>$rs['resp']['payment_no']]);
					//提现成功通知
					$tmplcontent = [];
					$tmplcontent['first'] = '您的提现申请已打款，请留意查收';
					$tmplcontent['remark'] = '请点击查看详情~';
					$tmplcontent['money'] = (string) round($record['money'],2);
					$tmplcontent['timet'] = date('Y-m-d H:i',$record['createtime']);
					\app\common\Wechat::sendtmpl(aid,$record['mid'],'tmpl_tixiansuccess',$tmplcontent,m_url('pages/my/usercenter'));
					//订阅消息
					$tmplcontent = [];
					$tmplcontent['amount1'] = $record['money'];
					$tmplcontent['thing3'] = '微信打款';
					$tmplcontent['time5'] = date('Y-m-d H:i');
					
					$tmplcontentnew = [];
					$tmplcontentnew['amount3'] = $record['money'];
					$tmplcontentnew['phrase9'] = '微信打款';
					$tmplcontentnew['date8'] = date('Y-m-d H:i');
					\app\common\Wechat::sendwxtmpl(aid,$record['mid'],'tmpl_tixiansuccess',$tmplcontentnew,'pages/my/usercenter',$tmplcontent);
					//短信通知
					if($this->member['tel']){
						\app\common\Sms::send(aid,$this->member['tel'],'tmpl_tixiansuccess',['money'=>$record['money']]);
					}
					return json(['status'=>1,'msg'=>$rs['msg']]);
				}
			}

			return $this->json(['status'=>1,'msg'=>'提交成功,请等待打款']);
		}
		$userinfo = Db::name('member')->where('id',mid)->field('id,yuebao_money,aliaccount,bankname,bankcarduser,bankcardnum')->find();
		//订阅消息
		$wx_tmplset = Db::name('wx_tmplset')->where('aid',aid)->find();
		$tmplids = [];
		if($wx_tmplset['tmpl_tixiansuccess_new']){
			$tmplids[] = $wx_tmplset['tmpl_tixiansuccess_new'];
		}elseif($wx_tmplset['tmpl_tixiansuccess']){
			$tmplids[] = $wx_tmplset['tmpl_tixiansuccess'];
		}
		if($wx_tmplset['tmpl_tixianerror_new']){
			$tmplids[] = $wx_tmplset['tmpl_tixianerror_new'];
		}elseif($wx_tmplset['tmpl_tixianerror']){
			$tmplids[] = $wx_tmplset['tmpl_tixianerror'];
		}
		$rdata = [];
		$rdata['status'] = 1;
		$rdata['userinfo'] = $userinfo;
		$rdata['sysset'] = $set;
		$rdata['tmplids'] = $tmplids;
		return $this->json($rdata);
	}

	//余额宝收益转到余额
    public function yuebao_turn_money()
    {
    	if(!getcustom('plug_yuebao')) {
			die;
		}
		$set = Db::name('admin_set')->where('aid',aid)->field('open_yuebao,yuebao_withdraw_time,yuebao_turn_yue')->find();
		if($set['open_yuebao'] !=1){
			return $this->json(['status'=>0,'msg'=>'余额宝功能未启用']);
		}
		if($set['yuebao_turn_yue'] !=1){
			return $this->json(['status'=>0,'msg'=>'该功能未启用']);
		}
		//查询上次提现、转余额时间
		$find_ytime = Db::name('member_yuebao_moneylog')
			->where('aid',aid)
			->where('mid',mid)
			->where('money','<',0)
			->where('type','>=',2)
			->where('type','<=',3)
			->field('createtime')
			->order('createtime desc')
			->find();
		if($find_ytime){
			//现在时间与上次时间差
			$cha = time()-$find_ytime['createtime'];

			//限制提现天数
			$wday  = 0;
			$wtime = 0;
			//单独设置天数
			if($this->member['yuebao_withdraw_time']>0){
				$wday = $this->member['yuebao_withdraw_time'];
				//转换天为秒
				$wtime = $this->member['yuebao_withdraw_time']*24*60*60;
			}else{
				//如果单独设置天数为负数，且总天数设置大于0
				if($this->member['yuebao_withdraw_time'] <0 && $set['yuebao_withdraw_time']>0){
					$wday = $set['yuebao_withdraw_time'];
					//转换天为秒
					$wtime = $set['yuebao_withdraw_time']*24*60*60;
				}
			}

			if($wtime>0 && $cha<$wtime){
				return $this->json(['status'=>0,'msg'=>t('余额宝').'收益'.$wday.'天可转'.t('余额').'一次']);
			}
		}
		$post = input('post.');

		$money = floatval($post['money']);
		if($money <= 0 || $money > $this->member['yuebao_money']){
			return $this->json(['status'=>0,'msg'=>'转入金额不正确']);
		}
		\app\common\Member::addmoney(aid,mid,$money,t('余额宝').'收益转'.t('余额'));
		\app\common\Member::addyuebaomoney(aid,mid,-$money,t('余额宝').'收益转'.t('余额'),3);
		return $this->json(['status'=>1,'msg'=>'转入成功']);
	}
	//余额宝明细
	public function yuebaolog(){
		$st = input('param.st');
		$pagenum = input('post.pagenum');
		if(!$pagenum) $pagenum = 1;
		$pernum = 20;
		$where = [];
		$where[] = ['aid','=',aid];
		$where[] = ['mid','=',mid];
		if($st ==1){//提现记录
			$datalist = Db::name('member_yuebao_withdrawlog')->field("id,money,txmoney,`status`,from_unixtime(createtime) createtime")->where($where)->page($pagenum,$pernum)->order('id desc')->select()->toArray();
			if(!$datalist) $datalist = [];
		}else{ //余额明细
			$datalist = Db::name('member_yuebao_moneylog')->field("id,money,`after`,from_unixtime(createtime) createtime,remark")->where($where)->page($pagenum,$pernum)->order('id desc')->select()->toArray();
			if(!$datalist) $datalist = [];
			foreach($datalist as $k=>$v){
				if(strpos($v['remark'],'商家充值，') === 0){
					$datalist[$k]['remark'] = '商家充值';
				}
			}
		}
		if($pagenum == 1){
			$canwithdraw = Db::name('admin_set')->where('aid',aid)->value('yuebao_withdraw');
		}
		return $this->json(['status'=>1,'data'=>$datalist,'canwithdraw'=>$canwithdraw]);
	}

	//注销账号
	public function delaccount(){
		$mid = mid.'';
		\app\model\Member::del(aid,$mid);
		sleep(2);
		return $this->json(['status'=>1,'msg'=>'账号已注销']);
	}

	public function setAgentCard()
    {
        if(request()->isPost()){
            $formdata = input('post.formdata/a');

            $info = [];
            $info['aid'] = aid;
            $info['mid'] = mid;
            $info['name'] = $formdata['name'];
            $info['shopname'] = $formdata['shopname'];
            $info['address'] = $formdata['address'];
            $info['tel'] = $formdata['tel'];
            $info['logo'] = $formdata['logo'];
            $info['pagecontent'] = json_encode(input('post.pagecontent'));
            $info['latitude'] = $formdata['latitude'];
            $info['longitude'] = $formdata['longitude'];

            $info['createtime'] = time();

            if($formdata['id']){
                Db::name('member_agent_card')->where('aid',aid)->where('mid',mid)->where('id',$formdata['id'])->update($info);
            }else{
                Db::name('member_agent_card')->insertGetId($info);
            }
            return $this->json(['status'=>1,'msg'=>'提交成功']);
        }
        $info = Db::name('member_agent_card')->where('aid',aid)->where('mid',mid)->find();
        $pagecontent = json_decode(\app\common\System::initpagecontent($info['pagecontent'],aid),true);
        if(!$pagecontent) $pagecontent = [];
        $rdata = [];
        $rdata['info'] = $info ? $info : [];
        $rdata['pagecontent'] = $pagecontent;
        return $this->json($rdata);
    }

    //元宝记录
    public function yuanbaolog(){
        if(getcustom('pay_yuanbao')) {
            $pagenum = input('post.pagenum');
            $st = input('post.st');
            if(!$pagenum) $pagenum = 1;
            $pernum = 20;
            $where = [];
            $where[] = ['aid','=',aid];
            $where[] = ['mid','=',mid];
            $datalist = Db::name('member_yuanbaolog')->field('id,yuanbao,after,remark,from_unixtime(createtime)createtime')->where($where)->page($pagenum,$pernum)->order('id desc')->select()->toArray();
            if(!$datalist) $datalist = [];
            if(request()->isPost()){
                if($pagenum == 1) {
                    $set = Db::name('admin_set')->where('aid', aid)->find();
                    $yuanbaoTransfer = $set['yuanbao_transfer'] ? true : false;
                }
                return $this->json(['status'=>1,'data'=>$datalist,'myyuanbao'=>$this->member['yuanbao'],'yuanbaoTransfer' => $yuanbaoTransfer] );
            }

            $count = Db::name('member_yuanbaolog')->where($where)->count();

            $rdata = [];
            $rdata['count'] = $count;
            $rdata['datalist'] = $datalist;
            $rdata['pernum'] = $pernum;
            $rdata['st'] = $st;
            $rdata['myyuanbao'] = $this->member['yuanbao'];
            $rdata['title'] = t('元宝')."明细";
            return $this->json($rdata);
        }
        
    }

    //元宝转送
    public function yuanbaoTransfer()
    {
        if(getcustom('pay_yuanbao')) {
            $set = Db::name('admin_set')->where('aid', aid)->find();
            if ($set['yuanbao_transfer'] != 1) {
                return $this->json(['status'=>0,'msg'=>t('元宝').'转赠未开启']);
            }
            //元宝转账现金比例
            $yuanbao_money_ratio = $set['yuanbao_money_ratio'];
            
            if(request()->isPost()){
                $mobile = input('post.mobile');
                $mid = input('post.mid/d');
                $integral = input('post.integral');
                if ($integral <= 0){
                    return $this->json(['status'=>0,'msg'=>'请输入正确的'.t('元宝').'数量']);
                }
                if (input('?post.mobile')) {
                    $info = Db::name('member')->where('aid', aid)->where('tel', $mobile)->find();
                }
                if (input('?post.mid')) {
                    $info = Db::name('member')->where('aid', aid)->where('id', $mid)->find();
                }

                if(!$info) return $this->json(['status'=>0,'msg'=>'未找到该'.t('会员')]);
                $user_id = $info['id'];

                if ($info['id'] == mid) {
                    return $this->json(['status'=>0,'msg'=>'不能转赠给自己']);
                }
                if ($integral > $this->member['yuanbao']){
                    return $this->json(['status'=>0,'msg'=>'您的'.t('元宝').'数量不足']);
                }

                $money = $integral*$yuanbao_money_ratio/100;
                $money = round($money,2);
                if($money<=0){
                    //直接转账
                    $rs = \app\common\Member::addyuanbao(aid,$user_id,$integral,sprintf("来自%s的".t('元宝')."转赠", $this->member["nickname"]));
                    if ($rs['status'] == 1) {
                        \app\common\Member::addyuanbao(aid,mid,$integral * -1, sprintf(t('元宝')."转赠给：%s",$info['nickname']));
                    }
                    return $this->json(['status'=>1, 'msg' => '转赠成功', 'url'=>m_url('my/usercenter').'/aid/'.aid]);
                }else{
                    $data = [];
                    $data['aid'] = aid;
                    $data['mid'] = mid;
                    $data['to_mid']   = $user_id;
                    $data['ordernum'] = 'Z'.date('ymdHis').rand(100000,999999);
                    $data['money']    = $money;
                    $data['yuanbao']  = $integral;
                    $data['create_time'] = time();

                    if($this->member['pid']){
                        $parent1 = Db::name('member')->where('aid',aid)->where('id',$this->member['pid'])->find();
                        if($parent1){
                            $agleveldata1 = Db::name('member_level')->where('aid',aid)->where('id',$parent1['levelid'])->find();
                            if($agleveldata1 && $agleveldata1['can_agent']!=0){
                                $data['parent1'] = $parent1['id'];
                                if($agleveldata1['commissiontype']==1){ //固定金额按单
                                    $data['parent1commission'] = $agleveldata1['commission1'];
                                }else{
                                    $data['parent1commission'] = $agleveldata1['commission1'] * $money * 0.01;
                                }
                            }
                        }
                    }
                    if($parent1['pid']){
                        $parent2 = Db::name('member')->where('aid',aid)->where('id',$parent1['pid'])->find();
                        if($parent2){
                            $agleveldata2 = Db::name('member_level')->where('aid',aid)->where('id',$parent2['levelid'])->find();
                            if($agleveldata2 && $agleveldata2['can_agent']>1){
                                $data['parent2'] = $parent2['id'];
                                if($agleveldata2['commissiontype']==1){ //固定金额按单
                                    $data['parent2commission'] = $agleveldata2['commission2'];
                                }else{
                                    $data['parent2commission'] = $agleveldata2['commission2'] * $money * 0.01;
                                }
                            }
                        }
                    }
                    if($parent2['pid']){
                        $parent3 = Db::name('member')->where('aid',aid)->where('id',$parent2['pid'])->find();
                        if($parent3){
                            $agleveldata3 = Db::name('member_level')->where('aid',aid)->where('id',$parent3['levelid'])->find();
                            if($agleveldata3 && $agleveldata3['can_agent']>2){
                                $data['parent3'] = $parent3['id'];
                                if($agleveldata3['commissiontype']==1){ //固定金额按单
                                    $data['parent3commission'] = $agleveldata3['commission3'];
                                }else{
                                    $data['parent3commission'] = $agleveldata3['commission3'] * $money * 0.01;
                                }
                            }
                        }
                    }

                    $insert_id = Db::name('member_yuanbao_transfer_order')->insertGetId($data);
                    if($insert_id){
                        $payorderid = \app\model\Payorder::createorder(aid,0,mid,'member_yuanbao_transfer',$insert_id,$data['ordernum'],t('元宝')."转赠给".$info['nickname'],$money,0);
                        $up = Db::name('member_yuanbao_transfer_order')->where('id',$insert_id)->update(['payorderid'=>$payorderid]);
                        return $this->json(['status'=>2, 'msg' => '提交成功','payorderid'=>$payorderid]);
                    }else{
                        return $this->json(['status'=>0, 'msg' => '提交失败']);
                    }
                }
            }

            $rdata['status'] = 1;
            $rdata['myyuanbao'] = $this->member['yuanbao'];
            $rdata['yuanbao_money_ratio'] = $yuanbao_money_ratio;
            $rdata['title'] = t('元宝')."转账";
            return $this->json($rdata);
        }
    }

    public function othermoneylog(){
    	if(getcustom('other_money')){
    		//是否有多账户权限
            $othermoney_status = Db::name('admin')->where('id',aid)->value('othermoney_status');
            if($othermoney_status != 1){
                return json(['status'=>0,'msg'=>'无权限操作']);
            }
	    	$type   = input('post.type');
	    	$st = input('param.st');
	        if($type == 'money2'){
	            $type_name = t('余额2');
	            $log_type  = 2;
	        }else if($type == 'money3'){
	            $type_name = t('余额3');
	            $log_type  = 3;
	        }else if($type == 'money4'){
	            $type_name = t('余额4');
	            $log_type  = 4;
	        }else if($type == 'money5'){
	            $type_name = t('余额5');
	            $log_type  = 5;
	        }else if($type == 'frozen_money'){
	            $type_name = t('冻结金额');
	            $log_type  = 0;
	        }else{
	            return json(['status'=>0,'msg'=>'操作类型错误']);
	        }

	        $pagenum = input('post.pagenum');
	        if(!$pagenum) $pagenum = 1;
	        $pernum = 20;
	        $where = [];
	        $where[] = ['aid','=',aid];
	        $where[] = ['mid','=',mid];
	        $where[] = ['type','=',$log_type];

	        if($st ==1){//提现记录
	            $datalist = Db::name('member_otherwithdrawlog')->field("id,money,txmoney,`status`,from_unixtime(createtime) createtime")->where($where)->page($pagenum,$pernum)->order('id desc')->select()->toArray();
	            if(!$datalist) $datalist = [];
	        }else{ //明细
	            $datalist = Db::name('member_othermoneylog')->field("id,money,`after`,from_unixtime(createtime) createtime,remark")->where($where)->page($pagenum,$pernum)->order('id desc')->select()->toArray();
	            if(!$datalist) $datalist = [];
	            foreach($datalist as $k=>$v){
	                if(strpos($v['remark'],'商家充值，') === 0){
	                    $datalist[$k]['remark'] = '商家充值';
	                }
	            }
	        }
	        if($pagenum == 1){
	            $canwithdraw = Db::name('admin_set')->where('aid',aid)->value('withdraw');
	        }
	        if($type == 'frozen_money'){
	             return $this->json(['status'=>1,'data'=>$datalist,'canwithdraw'=>$canwithdraw,'type_name'=>$type_name,'money'=>$this->member['frozen_money']]);
	        }else{
	             return $this->json(['status'=>1,'data'=>$datalist,'canwithdraw'=>$canwithdraw,'type_name'=>$type_name,]);
	        }
	    }
    }

    public function otherwithdraw(){
    	if(getcustom('other_money')){
    		//是否有多账户权限
            $othermoney_status = Db::name('admin')->where('id',aid)->value('othermoney_status');
            if($othermoney_status != 1){
                return json(['status'=>0,'msg'=>'无权限操作']);
            }
	        $set = Db::name('admin_set')->where('aid',aid)->field('withdraw_autotransfer,withdraw,withdrawmin,withdrawfee,withdraw_weixin,withdraw_aliaccount,withdraw_bankcard,othermoney_withdraw')->find();
	        $type   = input('type');
	        if($type == 'money2'){
	            $type_name    = t('余额2');
	            $log_type     = 2;
	            $field 	      = 'id,money2 as money,aliaccount,bankname,bankcarduser,bankcardnum';
	            $member_money = $this->member['money2'];
	        }else if($type == 'money3'){
	            $type_name    = t('余额3');
	            $log_type     = 3;
	            $field 	      = 'id,money3 as money,aliaccount,bankname,bankcarduser,bankcardnum';
	            $member_money = $this->member['money3'];
	        }else if($type == 'money4'){
	            $type_name    = t('余额4');
	            $log_type     = 4;
	            $field 	      = 'id,money4 as money,aliaccount,bankname,bankcarduser,bankcardnum';
	            $member_money = $this->member['money4'];
	        }else if($type == 'money5'){
	            $type_name    = t('余额5');
	            $log_type     = 5;
	            $field 	      = 'id,money5 as money,aliaccount,bankname,bankcarduser,bankcardnum';
	            $member_money = $this->member['money5'];
	        }else{
	            return json(['status'=>0,'msg'=>'操作类型错误']);
	        }
	        if(request()->isPost()){
	            $post = input('post.');

	            if($set['withdraw'] == 0 ){
	                return $this->json(['status'=>0,'msg'=>$type_name.'提现功能未开启']);
	            }
	            if(!$set['othermoney_withdraw']){
	                return $this->json(['status'=>0,'msg'=>$type_name.'提现功能未开启']);
	            }
	            if($post['paytype']=='支付宝' && $this->member['aliaccount']==''){
	                if($set['withdraw_aliaccount'] == 0)
	                    return $this->json(['status'=>0,'msg'=>'支付宝提现功能未开启']);
	                return $this->json(['status'=>0,'msg'=>'请先设置支付宝账号']);
	            }
	            if($post['paytype']=='银行卡' && ($this->member['bankname']==''||$this->member['bankcarduser']==''||$this->member['bankcardnum']=='')){
	                if($set['withdraw_bankcard'] == 0)
	                    return $this->json(['status'=>0,'msg'=>'银行卡提现功能未开启']);
	                return $this->json(['status'=>0,'msg'=>'请先设置完整银行卡信息']);
	            }
	            if($post['paytype'] == '微信钱包' && $set['withdraw_weixin'] == 0){
	                return $this->json(['status'=>0,'msg'=>'微信钱包提现功能未开启']);
	            }

	            $money = $post['money'];
	            if($money<=0 || $money < $set['withdrawmin']){
	                return $this->json(['status'=>0,'msg'=>'提现金额必须大于'.($set['withdrawmin']?$set['withdrawmin']:0)]);
	            }
	            if($money > $member_money){
	                return $this->json(['status'=>0,'msg'=>'可提现'.$type_name.'不足']);
	            }

	            $ordernum = date('ymdHis').aid.rand(1000,9999);
	            $record['aid'] = aid;
	            $record['mid'] = mid;
	            $record['createtime']= time();
	            $record['money'] = $money*(1-$set['withdrawfee']*0.01);
	            if($record['money'] <= 0) {
	                return $this->json(['status'=>0,'msg'=>'提现金额有误']);
	            }
	            $record['money'] = round($record['money'],2);
	            $record['txmoney'] = $money;
	            if($post['paytype']=='支付宝'){
	                $record['aliaccountname'] = $this->member['aliaccountname'];
	                $record['aliaccount'] = $this->member['aliaccount'];
	            }
	            if($post['paytype']=='银行卡'){
	                $record['bankname'] = $this->member['bankname'] . ($this->member['bankaddress'] ? ' '.$this->member['bankaddress'] : '');
	                $record['bankcarduser'] = $this->member['bankcarduser'];
	                $record['bankcardnum'] = $this->member['bankcardnum'];
	            }
	            $record['ordernum'] = $ordernum;
	            $record['paytype']  = $post['paytype'];
	            $record['platform'] = platform;
	            $record['type']     = $log_type;
	            $recordid = Db::name('member_otherwithdrawlog')->insertGetId($record);

	            \app\common\Member::addOtherMoney(aid,mid,$type,-$money,$type_name.'提现');

	            /*$tmplcontent = array();
	            $tmplcontent['first'] = '有客户申请'.$type_name.'提现';
	            $tmplcontent['remark'] = '点击进入查看~';
	            $tmplcontent['keyword1'] = $this->member['nickname'];
	            $tmplcontent['keyword2'] = date('Y-m-d H:i');
	            $tmplcontent['keyword3'] = $money.'元';
	            $tmplcontent['keyword4'] = $post['paytype'];
	            \app\common\Wechat::sendhttmpl(aid,0,'tmpl_withdraw',$tmplcontent,m_url('admin/finance/withdrawlog'));*/

	            /*$tmplcontent = [];
	            $tmplcontent['name3'] = $this->member['nickname'];
	            $tmplcontent['amount1'] = $money.'元';
	            $tmplcontent['date2'] = date('Y-m-d H:i');
	            $tmplcontent['thing4'] = '提现到'.$post['paytype'];
	            \app\common\Wechat::sendhtwxtmpl(aid,0,'tmpl_withdraw',$tmplcontent,'admin/finance/withdrawlog');*/

	            if($set['withdraw_autotransfer'] && ($post['paytype'] = '微信钱包' || $post['paytype'] = '银行卡')){
	                Db::name('member_otherwithdrawlog')->where('id',$recordid)->where('type',$log_type)->update(['status' => 1]);
	                $rs = \app\common\Wxpay::transfers(aid,mid,$record['money'],$record['ordernum'],platform,$type_name.'提现');
	                if($rs['status']==0){
	                    return json(['status'=>1,'msg'=>'提交成功,请等待打款']);
	                }else{
	                    Db::name('member_otherwithdrawlog')->where('id',$recordid)->where('type',$log_type)->update(['status' => 3]);
	                    Db::name('member_otherwithdrawlog')->where('aid',aid)->where('id',$recordid)->where('type',$log_type)->update(['status'=>3,'paytime'=>time(),'paynum'=>$rs['resp']['payment_no']]);
	                    //提现成功通知
	                    $tmplcontent = [];
	                    $tmplcontent['first'] = '您的'.$type_name.'提现申请已打款，请留意查收';
	                    $tmplcontent['remark'] = '请点击查看详情~';
	                    $tmplcontent['money'] = (string) round($record['money'],2);
	                    $tmplcontent['timet'] = date('Y-m-d H:i',$record['createtime']);
	                    \app\common\Wechat::sendtmpl(aid,$record['mid'],'tmpl_tixiansuccess',$tmplcontent,m_url('pages/my/usercenter'));
	                    //订阅消息
	                    $tmplcontent = [];
	                    $tmplcontent['amount1'] = $record['money'];
	                    $tmplcontent['thing3'] = '微信打款';
	                    $tmplcontent['time5'] = date('Y-m-d H:i');

	                    $tmplcontentnew = [];
	                    $tmplcontentnew['amount3'] = $record['money'];
	                    $tmplcontentnew['phrase9'] = '微信打款';
	                    $tmplcontentnew['date8'] = date('Y-m-d H:i');
	                    \app\common\Wechat::sendwxtmpl(aid,$record['mid'],'tmpl_tixiansuccess',$tmplcontentnew,'pages/my/usercenter',$tmplcontent);
	                    //短信通知
	                    if($this->member['tel']){
	                        \app\common\Sms::send(aid,$this->member['tel'],'tmpl_tixiansuccess',['money'=>$record['money']]);
	                    }
	                    return json(['status'=>1,'msg'=>$rs['msg']]);
	                }
	            }

	            return $this->json(['status'=>1,'msg'=>'提交成功,请等待打款']);
	        }
	        $userinfo = Db::name('member')->where('id',mid)->field($field)->find();
	        //订阅消息
	        $wx_tmplset = Db::name('wx_tmplset')->where('aid',aid)->find();
	        $tmplids = [];
	        if($wx_tmplset['tmpl_tixiansuccess_new']){
	            $tmplids[] = $wx_tmplset['tmpl_tixiansuccess_new'];
	        }elseif($wx_tmplset['tmpl_tixiansuccess']){
	            $tmplids[] = $wx_tmplset['tmpl_tixiansuccess'];
	        }
	        if($wx_tmplset['tmpl_tixianerror_new']){
	            $tmplids[] = $wx_tmplset['tmpl_tixianerror_new'];
	        }elseif($wx_tmplset['tmpl_tixianerror']){
	            $tmplids[] = $wx_tmplset['tmpl_tixianerror'];
	        }
	        $rdata = [];
	        $rdata['status']    = 1;
	        $rdata['userinfo']  = $userinfo;
	        $rdata['sysset']    = $set;
	        $rdata['tmplids']   = $tmplids;
	        $rdata['type_name'] = $type_name;

	        $rdata['canWithdraw'] = $set['othermoney_withdraw']?true:false;
	        return $this->json($rdata);
	    }
    }
}